.

.

标准库

1 - archive

1.1 - tar

tar

https://pkg.go.dev/archive/tar@go1.20.1

Package tar implements access to tar archives.

Tape archives (tar) are a file format for storing a sequence of files that can be read and written in a streaming manner. This package aims to cover most variations of the format, including those produced by GNU and BSD tar tools.

Example

常量

View Source

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
const (
	// Type '0' indicates a regular file.
	TypeReg = '0'

	// Deprecated: Use TypeReg instead.
	TypeRegA = '\x00'

	// Type '1' to '6' are header-only flags and may not have a data body.
	TypeLink    = '1' // Hard link
	TypeSymlink = '2' // Symbolic link
	TypeChar    = '3' // Character device node
	TypeBlock   = '4' // Block device node
	TypeDir     = '5' // Directory
	TypeFifo    = '6' // FIFO node

	// Type '7' is reserved.
	TypeCont = '7'

	// Type 'x' is used by the PAX format to store key-value records that
	// are only relevant to the next file.
	// This package transparently handles these types.
	TypeXHeader = 'x'

	// Type 'g' is used by the PAX format to store key-value records that
	// are relevant to all subsequent files.
	// This package only supports parsing and composing such headers,
	// but does not currently support persisting the global state across files.
	TypeXGlobalHeader = 'g'

	// Type 'S' indicates a sparse file in the GNU format.
	TypeGNUSparse = 'S'

	// Types 'L' and 'K' are used by the GNU format for a meta file
	// used to store the path or link name for the next file.
	// This package transparently handles these types.
	TypeGNULongName = 'L'
	TypeGNULongLink = 'K'
)

Type flags for Header.Typeflag.

变量

View Source

1
2
3
4
5
6
7
var (
	ErrHeader          = errors.New("archive/tar: invalid tar header")
	ErrWriteTooLong    = errors.New("archive/tar: write too long")
	ErrFieldTooLong    = errors.New("archive/tar: header field too long")
	ErrWriteAfterClose = errors.New("archive/tar: write after close")
	ErrInsecurePath    = errors.New("archive/tar: insecure file path")
)

函数

This section is empty.

类型

type Format <- go1.10

1
type Format int

Format represents the tar archive format.

The original tar format was introduced in Unix V7. Since then, there have been multiple competing formats attempting to standardize or extend the V7 format to overcome its limitations. The most common formats are the USTAR, PAX, and GNU formats, each with their own advantages and limitations.

The following table captures the capabilities of each format:

                  |  USTAR |       PAX |       GNU
------------------+--------+-----------+----------
Name              |   256B | unlimited | unlimited
Linkname          |   100B | unlimited | unlimited
Size              | uint33 | unlimited |    uint89
Mode              | uint21 |    uint21 |    uint57
Uid/Gid           | uint21 | unlimited |    uint57
Uname/Gname       |    32B | unlimited |       32B
ModTime           | uint33 | unlimited |     int89
AccessTime        |    n/a | unlimited |     int89
ChangeTime        |    n/a | unlimited |     int89
Devmajor/Devminor | uint21 |    uint21 |    uint57
------------------+--------+-----------+----------
string encoding   |  ASCII |     UTF-8 |    binary
sub-second times  |     no |       yes |        no
sparse files      |     no |       yes |       yes

The table’s upper portion shows the Header fields, where each format reports the maximum number of bytes allowed for each string field and the integer type used to store each numeric field (where timestamps are stored as the number of seconds since the Unix epoch).

The table’s lower portion shows specialized features of each format, such as supported string encodings, support for sub-second timestamps, or support for sparse files.

The Writer currently provides no support for sparse files.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
const (

	// FormatUnknown indicates that the format is unknown.
	FormatUnknown Format

	// FormatUSTAR represents the USTAR header format defined in POSIX.1-1988.
	//
	// While this format is compatible with most tar readers,
	// the format has several limitations making it unsuitable for some usages.
	// Most notably, it cannot support sparse files, files larger than 8GiB,
	// filenames larger than 256 characters, and non-ASCII filenames.
	//
	// Reference:
	//	http://pubs.opengroup.org/onlinepubs/9699919799/utilities/pax.html#tag_20_92_13_06
	FormatUSTAR

	// FormatPAX represents the PAX header format defined in POSIX.1-2001.
	//
	// PAX extends USTAR by writing a special file with Typeflag TypeXHeader
	// preceding the original header. This file contains a set of key-value
	// records, which are used to overcome USTAR's shortcomings, in addition to
	// providing the ability to have sub-second resolution for timestamps.
	//
	// Some newer formats add their own extensions to PAX by defining their
	// own keys and assigning certain semantic meaning to the associated values.
	// For example, sparse file support in PAX is implemented using keys
	// defined by the GNU manual (e.g., "GNU.sparse.map").
	//
	// Reference:
	//	http://pubs.opengroup.org/onlinepubs/009695399/utilities/pax.html
	FormatPAX

	// FormatGNU represents the GNU header format.
	//
	// The GNU header format is older than the USTAR and PAX standards and
	// is not compatible with them. The GNU format supports
	// arbitrary file sizes, filenames of arbitrary encoding and length,
	// sparse files, and other features.
	//
	// It is recommended that PAX be chosen over GNU unless the target
	// application can only parse GNU formatted archives.
	//
	// Reference:
	//	https://www.gnu.org/software/tar/manual/html_node/Standard.html
	FormatGNU
)

Constants to identify various tar formats.

(Format) String <- go1.10

1
func (f Format) String() string

type Header

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
type Header struct {
	// Typeflag is the type of header entry.
	// The zero value is automatically promoted to either TypeReg or TypeDir
	// depending on the presence of a trailing slash in Name.
	Typeflag byte

	Name     string // Name of file entry
	Linkname string // Target name of link (valid for TypeLink or TypeSymlink)

	Size  int64  // Logical file size in bytes
	Mode  int64  // Permission and mode bits
	Uid   int    // User ID of owner
	Gid   int    // Group ID of owner
	Uname string // User name of owner
	Gname string // Group name of owner

	// If the Format is unspecified, then Writer.WriteHeader rounds ModTime
	// to the nearest second and ignores the AccessTime and ChangeTime fields.
	//
	// To use AccessTime or ChangeTime, specify the Format as PAX or GNU.
	// To use sub-second resolution, specify the Format as PAX.
	ModTime    time.Time // Modification time
	AccessTime time.Time // Access time (requires either PAX or GNU support)
	ChangeTime time.Time // Change time (requires either PAX or GNU support)

	Devmajor int64 // Major device number (valid for TypeChar or TypeBlock)
	Devminor int64 // Minor device number (valid for TypeChar or TypeBlock)

	// Xattrs stores extended attributes as PAX records under the
	// "SCHILY.xattr." namespace.
	//
	// The following are semantically equivalent:
	//  h.Xattrs[key] = value
	//  h.PAXRecords["SCHILY.xattr."+key] = value
	//
	// When Writer.WriteHeader is called, the contents of Xattrs will take
	// precedence over those in PAXRecords.
	//
	// Deprecated: Use PAXRecords instead.
	Xattrs map[string]string

	// PAXRecords is a map of PAX extended header records.
	//
	// User-defined records should have keys of the following form:
	//	VENDOR.keyword
	// Where VENDOR is some namespace in all uppercase, and keyword may
	// not contain the '=' character (e.g., "GOLANG.pkg.version").
	// The key and value should be non-empty UTF-8 strings.
	//
	// When Writer.WriteHeader is called, PAX records derived from the
	// other fields in Header take precedence over PAXRecords.
	PAXRecords map[string]string

	// Format specifies the format of the tar header.
	//
	// This is set by Reader.Next as a best-effort guess at the format.
	// Since the Reader liberally reads some non-compliant files,
	// it is possible for this to be FormatUnknown.
	//
	// If the format is unspecified when Writer.WriteHeader is called,
	// then it uses the first format (in the order of USTAR, PAX, GNU)
	// capable of encoding this Header (see Format).
	Format Format
}

A Header represents a single header in a tar archive. Some fields may not be populated.

For forward compatibility, users that retrieve a Header from Reader.Next, mutate it in some ways, and then pass it back to Writer.WriteHeader should do so by creating a new Header and copying the fields that they are interested in preserving.

func FileInfoHeader <- go1.1

1
func FileInfoHeader(fi fs.FileInfo, link string) (*Header, error)

FileInfoHeader creates a partially-populated Header from fi. If fi describes a symlink, FileInfoHeader records link as the link target. If fi describes a directory, a slash is appended to the name.

Since fs.FileInfo’s Name method only returns the base name of the file it describes, it may be necessary to modify Header.Name to provide the full path name of the file.

(*Header) FileInfo <- go1.1

1
func (h *Header) FileInfo() fs.FileInfo

FileInfo returns an fs.FileInfo for the Header.

type Reader

1
2
3
type Reader struct {
	// contains filtered or unexported fields
}

Reader provides sequential access to the contents of a tar archive. Reader.Next advances to the next file in the archive (including the first), and then Reader can be treated as an io.Reader to access the file’s data.

func NewReader

1
func NewReader(r io.Reader) *Reader

NewReader creates a new Reader reading from r.

(*Reader) Next

1
func (tr *Reader) Next() (*Header, error)

Next advances to the next entry in the tar archive. The Header.Size determines how many bytes can be read for the next file. Any remaining data in the current file is automatically discarded. At the end of the archive, Next returns the error io.EOF.

If Next encounters a non-local name (as defined by filepath.IsLocal) and the GODEBUG environment variable contains tarinsecurepath=0, Next returns the header with an ErrInsecurePath error. A future version of Go may introduce this behavior by default. Programs that want to accept non-local names can ignore the ErrInsecurePath error and use the returned header.

(*Reader) Read

1
func (tr *Reader) Read(b []byte) (int, error)

Read reads from the current file in the tar archive. It returns (0, io.EOF) when it reaches the end of that file, until Next is called to advance to the next file.

If the current file is sparse, then the regions marked as a hole are read back as NUL-bytes.

Calling Read on special types like TypeLink, TypeSymlink, TypeChar, TypeBlock, TypeDir, and TypeFifo returns (0, io.EOF) regardless of what the Header.Size claims.

type Writer

1
2
3
type Writer struct {
	// contains filtered or unexported fields
}

Writer provides sequential writing of a tar archive. Write.WriteHeader begins a new file with the provided Header, and then Writer can be treated as an io.Writer to supply that file’s data.

func NewWriter

1
func NewWriter(w io.Writer) *Writer

NewWriter creates a new Writer writing to w.

(*Writer) Close

1
func (tw *Writer) Close() error

Close closes the tar archive by flushing the padding, and writing the footer. If the current file (from a prior call to WriteHeader) is not fully written, then this returns an error.

(*Writer) Flush

1
func (tw *Writer) Flush() error

Flush finishes writing the current file’s block padding. The current file must be fully written before Flush can be called.

This is unnecessary as the next call to WriteHeader or Close will implicitly flush out the file’s padding.

(*Writer) Write

1
func (tw *Writer) Write(b []byte) (int, error)

Write writes to the current file in the tar archive. Write returns the error ErrWriteTooLong if more than Header.Size bytes are written after WriteHeader.

Calling Write on special types like TypeLink, TypeSymlink, TypeChar, TypeBlock, TypeDir, and TypeFifo returns (0, ErrWriteTooLong) regardless of what the Header.Size claims.

(*Writer) WriteHeader

1
func (tw *Writer) WriteHeader(hdr *Header) error

WriteHeader writes hdr and prepares to accept the file’s contents. The Header.Size determines how many bytes can be written for the next file. If the current file is not fully written, then this returns an error. This implicitly flushes any padding necessary before writing the header.

1.2 - zip

zip

https://pkg.go.dev/archive/zip@go1.20.1

Package zip provides support for reading and writing ZIP archives.

See the ZIP specification for details.

This package does not support disk spanning.

A note about ZIP64:

To be backwards compatible the FileHeader has both 32 and 64 bit Size fields. The 64 bit fields will always contain the correct value and for normal archives both fields will be the same. For files requiring the ZIP64 format the 32 bit fields will be 0xffffffff and the 64 bit fields must be used instead.

常量

View Source

1
2
3
4
const (
	Store   uint16 = 0 // no compression
	Deflate uint16 = 8 // DEFLATE compressed
)

Compression methods.

变量

View Source

1
2
3
4
5
6
var (
	ErrFormat       = errors.New("zip: not a valid zip file")
	ErrAlgorithm    = errors.New("zip: unsupported compression algorithm")
	ErrChecksum     = errors.New("zip: checksum error")
	ErrInsecurePath = errors.New("zip: insecure file path")
)

函数

func RegisterCompressor <- go1.2

1
func RegisterCompressor(method uint16, comp Compressor)

RegisterCompressor registers custom compressors for a specified method ID. The common methods Store and Deflate are built in.

func RegisterDecompressor <- go1.2

1
func RegisterDecompressor(method uint16, dcomp Decompressor)

RegisterDecompressor allows custom decompressors for a specified method ID. The common methods Store and Deflate are built in.

类型

type Compressor <- go1.2

1
type Compressor func(w io.Writer) (io.WriteCloser, error)

A Compressor returns a new compressing writer, writing to w. The WriteCloser’s Close method must be used to flush pending data to w. The Compressor itself must be safe to invoke from multiple goroutines simultaneously, but each returned writer will be used only by one goroutine at a time.

type Decompressor <- go1.2

1
type Decompressor func(r io.Reader) io.ReadCloser

A Decompressor returns a new decompressing reader, reading from r. The ReadCloser’s Close method must be used to release associated resources. The Decompressor itself must be safe to invoke from multiple goroutines simultaneously, but each returned reader will be used only by one goroutine at a time.

type File

1
2
3
4
type File struct {
	FileHeader
	// contains filtered or unexported fields
}

A File is a single file in a ZIP archive. The file information is in the embedded FileHeader. The file content can be accessed by calling Open.

(*File) DataOffset <- go1.2

1
func (f *File) DataOffset() (offset int64, err error)

DataOffset returns the offset of the file’s possibly-compressed data, relative to the beginning of the zip file.

Most callers should instead use Open, which transparently decompresses data and verifies checksums.

(*File) Open

1
func (f *File) Open() (io.ReadCloser, error)

Open returns a ReadCloser that provides access to the File’s contents. Multiple files may be read concurrently.

(*File) OpenRaw <- go1.17

1
func (f *File) OpenRaw() (io.Reader, error)

OpenRaw returns a Reader that provides access to the File’s contents without decompression.

type FileHeader

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
type FileHeader struct {
	// Name is the name of the file.
	//
	// It must be a relative path, not start with a drive letter (such as "C:"),
	// and must use forward slashes instead of back slashes. A trailing slash
	// indicates that this file is a directory and should have no data.
	Name string

	// Comment is any arbitrary user-defined string shorter than 64KiB.
	Comment string

	// NonUTF8 indicates that Name and Comment are not encoded in UTF-8.
	//
	// By specification, the only other encoding permitted should be CP-437,
	// but historically many ZIP readers interpret Name and Comment as whatever
	// the system's local character encoding happens to be.
	//
	// This flag should only be set if the user intends to encode a non-portable
	// ZIP file for a specific localized region. Otherwise, the Writer
	// automatically sets the ZIP format's UTF-8 flag for valid UTF-8 strings.
	NonUTF8 bool

	CreatorVersion uint16
	ReaderVersion  uint16
	Flags          uint16

	// Method is the compression method. If zero, Store is used.
	Method uint16

	// Modified is the modified time of the file.
	//
	// When reading, an extended timestamp is preferred over the legacy MS-DOS
	// date field, and the offset between the times is used as the timezone.
	// If only the MS-DOS date is present, the timezone is assumed to be UTC.
	//
	// When writing, an extended timestamp (which is timezone-agnostic) is
	// always emitted. The legacy MS-DOS date field is encoded according to the
	// location of the Modified time.
	Modified time.Time

	// ModifiedTime is an MS-DOS-encoded time.
	//
	// Deprecated: Use Modified instead.
	ModifiedTime uint16

	// ModifiedDate is an MS-DOS-encoded date.
	//
	// Deprecated: Use Modified instead.
	ModifiedDate uint16

	// CRC32 is the CRC32 checksum of the file content.
	CRC32 uint32

	// CompressedSize is the compressed size of the file in bytes.
	// If either the uncompressed or compressed size of the file
	// does not fit in 32 bits, CompressedSize is set to ^uint32(0).
	//
	// Deprecated: Use CompressedSize64 instead.
	CompressedSize uint32

	// UncompressedSize is the compressed size of the file in bytes.
	// If either the uncompressed or compressed size of the file
	// does not fit in 32 bits, CompressedSize is set to ^uint32(0).
	//
	// Deprecated: Use UncompressedSize64 instead.
	UncompressedSize uint32

	// CompressedSize64 is the compressed size of the file in bytes.
	CompressedSize64 uint64

	// UncompressedSize64 is the uncompressed size of the file in bytes.
	UncompressedSize64 uint64

	Extra         []byte
	ExternalAttrs uint32 // Meaning depends on CreatorVersion
}

FileHeader describes a file within a ZIP file. See the ZIP specification for details.

func FileInfoHeader

1
func FileInfoHeader(fi fs.FileInfo) (*FileHeader, error)

FileInfoHeader creates a partially-populated FileHeader from an fs.FileInfo. Because fs.FileInfo’s Name method returns only the base name of the file it describes, it may be necessary to modify the Name field of the returned header to provide the full path name of the file. If compression is desired, callers should set the FileHeader.Method field; it is unset by default.

(*FileHeader) FileInfo

1
func (h *FileHeader) FileInfo() fs.FileInfo

FileInfo returns an fs.FileInfo for the FileHeader.

Example

(*FileHeader) Mode

1
func (h *FileHeader) Mode() (mode fs.FileMode)

Mode returns the permission and mode bits for the FileHeader.

Example

(*FileHeader) SetMode

1
func (h *FileHeader) SetMode(mode fs.FileMode)

SetMode changes the permission and mode bits for the FileHeader.

type ReadCloser

1
2
3
4
type ReadCloser struct {
	Reader
	// contains filtered or unexported fields
}

A ReadCloser is a Reader that must be closed when no longer needed.

func OpenReader

1
func OpenReader(name string) (*ReadCloser, error)

OpenReader will open the Zip file specified by name and return a ReadCloser.

(*ReadCloser) Close

1
func (rc *ReadCloser) Close() error

Close closes the Zip file, rendering it unusable for I/O.

type Reader

1
2
3
4
5
type Reader struct {
	File    []*File
	Comment string
	// contains filtered or unexported fields
}

A Reader serves content from a ZIP archive.

Example

func NewReader

1
func NewReader(r io.ReaderAt, size int64) (*Reader, error)

NewReader returns a new Reader reading from r, which is assumed to have the given size in bytes.

If any file inside the archive uses a non-local name (as defined by filepath.IsLocal) or a name containing backslashes and the GODEBUG environment variable contains zipinsecurepath=0, NewReader returns the reader with an ErrInsecurePath error. A future version of Go may introduce this behavior by default. Programs that want to accept non-local names can ignore the ErrInsecurePath error and use the returned reader.

(*Reader) Open <- go1.16

1
func (r *Reader) Open(name string) (fs.File, error)

Open opens the named file in the ZIP archive, using the semantics of fs.FS.Open: paths are always slash separated, with no leading / or ../ elements.

(*Reader) RegisterDecompressor <- go1.6

1
func (z *Reader) RegisterDecompressor(method uint16, dcomp Decompressor)

RegisterDecompressor registers or overrides a custom decompressor for a specific method ID. If a decompressor for a given method is not found, Reader will default to looking up the decompressor at the package level.

type Writer

1
2
3
type Writer struct {
	// contains filtered or unexported fields
}

Writer implements a zip file writer.

Example

func NewWriter

1
func NewWriter(w io.Writer) *Writer

NewWriter returns a new Writer writing a zip file to w.

(*Writer) Close

1
func (w *Writer) Close() error

Close finishes writing the zip file by writing the central directory. It does not close the underlying writer.

(*Writer) Copy <- go1.17

1
func (w *Writer) Copy(f *File) error

Copy copies the file f (obtained from a Reader) into w. It copies the raw form directly bypassing decompression, compression, and validation.

(*Writer) Create

1
func (w *Writer) Create(name string) (io.Writer, error)

Create adds a file to the zip file using the provided name. It returns a Writer to which the file contents should be written. The file contents will be compressed using the Deflate method. The name must be a relative path: it must not start with a drive letter (e.g. C:) or leading slash, and only forward slashes are allowed. To create a directory instead of a file, add a trailing slash to the name. The file’s contents must be written to the io.Writer before the next call to Create, CreateHeader, or Close.

(*Writer) CreateHeader

1
func (w *Writer) CreateHeader(fh *FileHeader) (io.Writer, error)

CreateHeader adds a file to the zip archive using the provided FileHeader for the file metadata. Writer takes ownership of fh and may mutate its fields. The caller must not modify fh after calling CreateHeader.

This returns a Writer to which the file contents should be written. The file’s contents must be written to the io.Writer before the next call to Create, CreateHeader, CreateRaw, or Close.

(*Writer) CreateRaw <- go1.17

1
func (w *Writer) CreateRaw(fh *FileHeader) (io.Writer, error)

CreateRaw adds a file to the zip archive using the provided FileHeader and returns a Writer to which the file contents should be written. The file’s contents must be written to the io.Writer before the next call to Create, CreateHeader, CreateRaw, or Close.

In contrast to CreateHeader, the bytes passed to Writer are not compressed.

(*Writer) Flush <- go1.4

1
func (w *Writer) Flush() error

Flush flushes any buffered data to the underlying writer. Calling Flush is not normally necessary; calling Close is sufficient.

(*Writer) RegisterCompressor <- go1.6

1
func (w *Writer) RegisterCompressor(method uint16, comp Compressor)

RegisterCompressor registers or overrides a custom compressor for a specific method ID. If a compressor for a given method is not found, Writer will default to looking up the compressor at the package level.

Example

(*Writer) SetComment <- go1.10

1
func (w *Writer) SetComment(comment string) error

SetComment sets the end-of-central-directory comment field. It can only be called before Close.

(*Writer) SetOffset <- go1.5

1
func (w *Writer) SetOffset(n int64)

SetOffset sets the offset of the beginning of the zip data within the underlying writer. It should be used when the zip data is appended to an existing file, such as a binary executable. It must be called before any data is written.

2 - compress

2.1 - bzip2

bzip2

https://pkg.go.dev/compress/bzip2@go1.20.1

Package bzip2 implements bzip2 decompression.

常量

This section is empty.

变量

This section is empty.

函数

func NewReader

1
func NewReader(r io.Reader) io.Reader

NewReader returns an io.Reader which decompresses bzip2 data from r. If r does not also implement io.ByteReader, the decompressor may read more data than necessary from r.

类型

type StructuralError

1
type StructuralError string

A StructuralError is returned when the bzip2 data is found to be syntactically invalid.

(StructuralError) Error

1
func (s StructuralError) Error() string

2.2 - flate

flate

https://pkg.go.dev/compress/flate@go1.20.1

Package flate implements the DEFLATE compressed data format, described in RFC 1951. The gzip and zlib packages implement access to DEFLATE-based file formats.

Example
Example
Example

常量

View Source

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
const (
	NoCompression      = 0
	BestSpeed          = 1
	BestCompression    = 9
	DefaultCompression = -1

	// HuffmanOnly disables Lempel-Ziv match searching and only performs Huffman
	// entropy encoding. This mode is useful in compressing data that has
	// already been compressed with an LZ style algorithm (e.g. Snappy or LZ4)
	// that lacks an entropy encoder. Compression gains are achieved when
	// certain bytes in the input stream occur more frequently than others.
	//
	// Note that HuffmanOnly produces a compressed output that is
	// RFC 1951 compliant. That is, any valid DEFLATE decompressor will
	// continue to be able to decompress this output.
	HuffmanOnly = -2
)

变量

This section is empty.

函数

func NewReader

1
func NewReader(r io.Reader) io.ReadCloser

NewReader returns a new ReadCloser that can be used to read the uncompressed version of r. If r does not also implement io.ByteReader, the decompressor may read more data than necessary from r. The reader returns io.EOF after the final block in the DEFLATE stream has been encountered. Any trailing data after the final block is ignored.

The ReadCloser returned by NewReader also implements Resetter.

func NewReaderDict

1
func NewReaderDict(r io.Reader, dict []byte) io.ReadCloser

NewReaderDict is like NewReader but initializes the reader with a preset dictionary. The returned Reader behaves as if the uncompressed data stream started with the given dictionary, which has already been read. NewReaderDict is typically used to read data compressed by NewWriterDict.

The ReadCloser returned by NewReader also implements Resetter.

类型

type CorruptInputError

1
type CorruptInputError int64

A CorruptInputError reports the presence of corrupt input at a given offset.

(CorruptInputError) Error

1
func (e CorruptInputError) Error() string

type InternalError

1
type InternalError string

An InternalError reports an error in the flate code itself.

(InternalError) Error

1
func (e InternalError) Error() string
Example

type Reader

1
2
3
4
type Reader interface {
	io.Reader
	io.ByteReader
}

The actual read interface needed by NewReader. If the passed in io.Reader does not also have ReadByte, the NewReader will introduce its own buffering.

type Resetter <- go1.4

1
2
3
4
5
type Resetter interface {
	// Reset discards any buffered data and resets the Resetter as if it was
	// newly initialized with the given reader.
	Reset(r io.Reader, dict []byte) error
}

Resetter resets a ReadCloser returned by NewReader or NewReaderDict to switch to a new underlying Reader. This permits reusing a ReadCloser instead of allocating a new one.

Example

type Writer

1
2
3
type Writer struct {
	// contains filtered or unexported fields
}

A Writer takes data written to it and writes the compressed form of that data to an underlying writer (see NewWriter).

func NewWriter

1
func NewWriter(w io.Writer, level int) (*Writer, error)

NewWriter returns a new Writer compressing data at the given level. Following zlib, levels range from 1 (BestSpeed) to 9 (BestCompression); higher levels typically run slower but compress more. Level 0 (NoCompression) does not attempt any compression; it only adds the necessary DEFLATE framing. Level -1 (DefaultCompression) uses the default compression level. Level -2 (HuffmanOnly) will use Huffman compression only, giving a very fast compression for all types of input, but sacrificing considerable compression efficiency.

If level is in the range [-2, 9] then the error returned will be nil. Otherwise the error returned will be non-nil.

func NewWriterDict

1
func NewWriterDict(w io.Writer, level int, dict []byte) (*Writer, error)

NewWriterDict is like NewWriter but initializes the new Writer with a preset dictionary. The returned Writer behaves as if the dictionary had been written to it without producing any compressed output. The compressed data written to w can only be decompressed by a Reader initialized with the same dictionary.

(*Writer) Close

1
func (w *Writer) Close() error

Close flushes and closes the writer.

(*Writer) Flush

1
func (w *Writer) Flush() error

Flush flushes any pending data to the underlying writer. It is useful mainly in compressed network protocols, to ensure that a remote reader has enough data to reconstruct a packet. Flush does not return until the data has been written. Calling Flush when there is no pending data still causes the Writer to emit a sync marker of at least 4 bytes. If the underlying writer returns an error, Flush returns that error.

In the terminology of the zlib library, Flush is equivalent to Z_SYNC_FLUSH.

(*Writer) Reset <- go1.2

1
func (w *Writer) Reset(dst io.Writer)

Reset discards the writer’s state and makes it equivalent to the result of NewWriter or NewWriterDict called with dst and w’s level and dictionary.

(*Writer) Write

1
func (w *Writer) Write(data []byte) (n int, err error)

Write writes data to w, which will eventually write the compressed form of data to its underlying writer.

2.3 - gzip

gzip

https://pkg.go.dev/compress/gzip@go1.20.1

Package gzip implements reading and writing of gzip format compressed files, as specified in RFC 1952.

Example
Example

常量

View Source

1
2
3
4
5
6
7
const (
	NoCompression      = flate.NoCompression
	BestSpeed          = flate.BestSpeed
	BestCompression    = flate.BestCompression
	DefaultCompression = flate.DefaultCompression
	HuffmanOnly        = flate.HuffmanOnly
)

These constants are copied from the flate package, so that code that imports “compress/gzip” does not also have to import “compress/flate”.

变量

View Source

1
2
3
4
5
6
var (
	// ErrChecksum is returned when reading GZIP data that has an invalid checksum.
	ErrChecksum = errors.New("gzip: invalid checksum")
	// ErrHeader is returned when reading GZIP data that has an invalid header.
	ErrHeader = errors.New("gzip: invalid header")
)

函数

This section is empty.

类型

type Header

1
2
3
4
5
6
7
type Header struct {
	Comment string    // comment
	Extra   []byte    // "extra data"
	ModTime time.Time // modification time
	Name    string    // file name
	OS      byte      // operating system type
}

The gzip file stores a header giving metadata about the compressed file. That header is exposed as the fields of the Writer and Reader structs.

Strings must be UTF-8 encoded and may only contain Unicode code points U+0001 through U+00FF, due to limitations of the GZIP file format.

type Reader

1
2
3
4
type Reader struct {
	Header // valid after NewReader or Reader.Reset
	// contains filtered or unexported fields
}

A Reader is an io.Reader that can be read to retrieve uncompressed data from a gzip-format compressed file.

In general, a gzip file can be a concatenation of gzip files, each with its own header. Reads from the Reader return the concatenation of the uncompressed data of each. Only the first header is recorded in the Reader fields.

Gzip files store a length and checksum of the uncompressed data. The Reader will return an ErrChecksum when Read reaches the end of the uncompressed data if it does not have the expected length or checksum. Clients should treat data returned by Read as tentative until they receive the io.EOF marking the end of the data.

func NewReader

1
func NewReader(r io.Reader) (*Reader, error)

NewReader creates a new Reader reading the given reader. If r does not also implement io.ByteReader, the decompressor may read more data than necessary from r.

It is the caller’s responsibility to call Close on the Reader when done.

The Reader.Header fields will be valid in the Reader returned.

(*Reader) Close

1
func (z *Reader) Close() error

Close closes the Reader. It does not close the underlying io.Reader. In order for the GZIP checksum to be verified, the reader must be fully consumed until the io.EOF.

(*Reader) Multistream <- go1.4

1
func (z *Reader) Multistream(ok bool)

Multistream controls whether the reader supports multistream files.

If enabled (the default), the Reader expects the input to be a sequence of individually gzipped data streams, each with its own header and trailer, ending at EOF. The effect is that the concatenation of a sequence of gzipped files is treated as equivalent to the gzip of the concatenation of the sequence. This is standard behavior for gzip readers.

Calling Multistream(false) disables this behavior; disabling the behavior can be useful when reading file formats that distinguish individual gzip data streams or mix gzip data streams with other data streams. In this mode, when the Reader reaches the end of the data stream, Read returns io.EOF. The underlying reader must implement io.ByteReader in order to be left positioned just after the gzip stream. To start the next stream, call z.Reset(r) followed by z.Multistream(false). If there is no next stream, z.Reset(r) will return io.EOF.

Example

(*Reader) Read

1
func (z *Reader) Read(p []byte) (n int, err error)

Read implements io.Reader, reading uncompressed bytes from its underlying Reader.

(*Reader) Reset <- go1.3

1
func (z *Reader) Reset(r io.Reader) error

Reset discards the Reader z’s state and makes it equivalent to the result of its original state from NewReader, but reading from r instead. This permits reusing a Reader rather than allocating a new one.

type Writer

1
2
3
4
type Writer struct {
	Header // written at first call to Write, Flush, or Close
	// contains filtered or unexported fields
}

A Writer is an io.WriteCloser. Writes to a Writer are compressed and written to w.

func NewWriter

1
func NewWriter(w io.Writer) *Writer

NewWriter returns a new Writer. Writes to the returned writer are compressed and written to w.

It is the caller’s responsibility to call Close on the Writer when done. Writes may be buffered and not flushed until Close.

Callers that wish to set the fields in Writer.Header must do so before the first call to Write, Flush, or Close.

func NewWriterLevel

1
func NewWriterLevel(w io.Writer, level int) (*Writer, error)

NewWriterLevel is like NewWriter but specifies the compression level instead of assuming DefaultCompression.

The compression level can be DefaultCompression, NoCompression, HuffmanOnly or any integer value between BestSpeed and BestCompression inclusive. The error returned will be nil if the level is valid.

(*Writer) Close

1
func (z *Writer) Close() error

Close closes the Writer by flushing any unwritten data to the underlying io.Writer and writing the GZIP footer. It does not close the underlying io.Writer.

(*Writer) Flush <- go1.1

1
func (z *Writer) Flush() error

Flush flushes any pending compressed data to the underlying writer.

It is useful mainly in compressed network protocols, to ensure that a remote reader has enough data to reconstruct a packet. Flush does not return until the data has been written. If the underlying writer returns an error, Flush returns that error.

In the terminology of the zlib library, Flush is equivalent to Z_SYNC_FLUSH.

(*Writer) Reset <- go1.2

1
func (z *Writer) Reset(w io.Writer)

Reset discards the Writer z’s state and makes it equivalent to the result of its original state from NewWriter or NewWriterLevel, but writing to w instead. This permits reusing a Writer rather than allocating a new one.

(*Writer) Write

1
func (z *Writer) Write(p []byte) (int, error)

Write writes a compressed form of p to the underlying io.Writer. The compressed bytes are not necessarily flushed until the Writer is closed.

2.4 - lzw

lzw

https://pkg.go.dev/compress/lzw@go1.20.1

Package lzw implements the Lempel-Ziv-Welch compressed data format, described in T. A. Welch, “A Technique for High-Performance Data Compression”, Computer, 17(6) (June 1984), pp 8-19.

In particular, it implements LZW as used by the GIF and PDF file formats, which means variable-width codes up to 12 bits and the first two non-literal codes are a clear code and an EOF code.

The TIFF file format uses a similar but incompatible version of the LZW algorithm. See the golang.org/x/image/tiff/lzw package for an implementation.

常量

This section is empty.

变量

This section is empty.

函数

func NewReader

1
func NewReader(r io.Reader, order Order, litWidth int) io.ReadCloser

NewReader creates a new io.ReadCloser. Reads from the returned io.ReadCloser read and decompress data from r. If r does not also implement io.ByteReader, the decompressor may read more data than necessary from r. It is the caller’s responsibility to call Close on the ReadCloser when finished reading. The number of bits to use for literal codes, litWidth, must be in the range [2,8] and is typically 8. It must equal the litWidth used during compression.

It is guaranteed that the underlying type of the returned io.ReadCloser is a *Reader.

func NewWriter

1
func NewWriter(w io.Writer, order Order, litWidth int) io.WriteCloser

NewWriter creates a new io.WriteCloser. Writes to the returned io.WriteCloser are compressed and written to w. It is the caller’s responsibility to call Close on the WriteCloser when finished writing. The number of bits to use for literal codes, litWidth, must be in the range [2,8] and is typically 8. Input bytes must be less than 1«litWidth.

It is guaranteed that the underlying type of the returned io.WriteCloser is a *Writer.

类型

type Order

1
type Order int

Order specifies the bit ordering in an LZW data stream.

1
2
3
4
5
6
7
const (
	// LSB means Least Significant Bits first, as used in the GIF file format.
	LSB Order = iota
	// MSB means Most Significant Bits first, as used in the TIFF and PDF
	// file formats.
	MSB
)

type Reader <- go1.17

1
2
3
type Reader struct {
	// contains filtered or unexported fields
}

Reader is an io.Reader which can be used to read compressed data in the LZW format.

(*Reader) Close <- go1.17

1
func (r *Reader) Close() error

Close closes the Reader and returns an error for any future read operation. It does not close the underlying io.Reader.

(*Reader) Read <- go1.17

1
func (r *Reader) Read(b []byte) (int, error)

Read implements io.Reader, reading uncompressed bytes from its underlying Reader.

(*Reader) Reset <- go1.17

1
func (r *Reader) Reset(src io.Reader, order Order, litWidth int)

Reset clears the Reader’s state and allows it to be reused again as a new Reader.

type Writer <- go1.17

1
2
3
type Writer struct {
	// contains filtered or unexported fields
}

Writer is an LZW compressor. It writes the compressed form of the data to an underlying writer (see NewWriter).

(*Writer) Close <- go1.17

1
func (w *Writer) Close() error

Close closes the Writer, flushing any pending output. It does not close w’s underlying writer.

(*Writer) Reset <- go1.17

1
func (w *Writer) Reset(dst io.Writer, order Order, litWidth int)

Reset clears the Writer’s state and allows it to be reused again as a new Writer.

(*Writer) Write <- go1.17

1
func (w *Writer) Write(p []byte) (n int, err error)

Write writes a compressed representation of p to w’s underlying writer.

2.5 - zlib

zlib

https://pkg.go.dev/compress/zlib@go1.20.1

Package zlib implements reading and writing of zlib format compressed data, as specified in RFC 1950.

The implementation provides filters that uncompress during reading and compress during writing. For example, to write compressed data to a buffer:

1
2
3
4
var b bytes.Buffer
w := zlib.NewWriter(&b)
w.Write([]byte("hello, world\n"))
w.Close()

and to read that data back:

r, err := zlib.NewReader(&b)
io.Copy(os.Stdout, r)
r.Close()

常量

View Source

1
2
3
4
5
6
7
const (
	NoCompression      = flate.NoCompression
	BestSpeed          = flate.BestSpeed
	BestCompression    = flate.BestCompression
	DefaultCompression = flate.DefaultCompression
	HuffmanOnly        = flate.HuffmanOnly
)

These constants are copied from the flate package, so that code that imports “compress/zlib” does not also have to import “compress/flate”.

变量

View Source

1
2
3
4
5
6
7
8
var (
	// ErrChecksum is returned when reading ZLIB data that has an invalid checksum.
	ErrChecksum = errors.New("zlib: invalid checksum")
	// ErrDictionary is returned when reading ZLIB data that has an invalid dictionary.
	ErrDictionary = errors.New("zlib: invalid dictionary")
	// ErrHeader is returned when reading ZLIB data that has an invalid header.
	ErrHeader = errors.New("zlib: invalid header")
)

函数

func NewReader

1
func NewReader(r io.Reader) (io.ReadCloser, error)

NewReader creates a new ReadCloser. Reads from the returned ReadCloser read and decompress data from r. If r does not implement io.ByteReader, the decompressor may read more data than necessary from r. It is the caller’s responsibility to call Close on the ReadCloser when done.

The ReadCloser returned by NewReader also implements Resetter.

Example

func NewReaderDict

1
func NewReaderDict(r io.Reader, dict []byte) (io.ReadCloser, error)

NewReaderDict is like NewReader but uses a preset dictionary. NewReaderDict ignores the dictionary if the compressed data does not refer to it. If the compressed data refers to a different dictionary, NewReaderDict returns ErrDictionary.

The ReadCloser returned by NewReaderDict also implements Resetter.

类型

type Resetter <- go1.4

1
2
3
4
5
type Resetter interface {
	// Reset discards any buffered data and resets the Resetter as if it was
	// newly initialized with the given reader.
	Reset(r io.Reader, dict []byte) error
}

Resetter resets a ReadCloser returned by NewReader or NewReaderDict to switch to a new underlying Reader. This permits reusing a ReadCloser instead of allocating a new one.

type Writer

1
2
3
type Writer struct {
	// contains filtered or unexported fields
}

A Writer takes data written to it and writes the compressed form of that data to an underlying writer (see NewWriter).

func NewWriter

1
func NewWriter(w io.Writer) *Writer

NewWriter creates a new Writer. Writes to the returned Writer are compressed and written to w.

It is the caller’s responsibility to call Close on the Writer when done. Writes may be buffered and not flushed until Close.

Example

func NewWriterLevel

1
func NewWriterLevel(w io.Writer, level int) (*Writer, error)

NewWriterLevel is like NewWriter but specifies the compression level instead of assuming DefaultCompression.

The compression level can be DefaultCompression, NoCompression, HuffmanOnly or any integer value between BestSpeed and BestCompression inclusive. The error returned will be nil if the level is valid.

func NewWriterLevelDict

1
func NewWriterLevelDict(w io.Writer, level int, dict []byte) (*Writer, error)

NewWriterLevelDict is like NewWriterLevel but specifies a dictionary to compress with.

The dictionary may be nil. If not, its contents should not be modified until the Writer is closed.

(*Writer) Close

1
func (z *Writer) Close() error

Close closes the Writer, flushing any unwritten data to the underlying io.Writer, but does not close the underlying io.Writer.

(*Writer) Flush

1
func (z *Writer) Flush() error

Flush flushes the Writer to its underlying io.Writer.

(*Writer) Reset <- go1.2

1
func (z *Writer) Reset(w io.Writer)

Reset clears the state of the Writer z such that it is equivalent to its initial state from NewWriterLevel or NewWriterLevelDict, but instead writing to w.

(*Writer) Write

1
func (z *Writer) Write(p []byte) (n int, err error)

Write writes a compressed form of p to the underlying io.Writer. The compressed bytes are not necessarily flushed until the Writer is closed or explicitly flushed.

3 - container

3.1 - heap

heap

https://pkg.go.dev/container/heap@go1.20.1

Package heap provides heap operations for any type that implements heap.Interface. A heap is a tree with the property that each node is the minimum-valued node in its subtree.

包heap为任何实现heap.Interface的类型提供堆操作。堆是一棵树,其属性是每个节点都是其子树中的最小值节点。

The minimum element in the tree is the root, at index 0.

树中的最小元素是根,索引为0。

A heap is a common way to implement a priority queue. To build a priority queue, implement the Heap interface with the (negative) priority as the ordering for the Less method, so Push adds items while Pop removes the highest-priority item from the queue. The Examples include such an implementation; the file example_pq_test.go has the complete source.

heap 是实现优先级队列的一种常见方式。要建立一个优先级队列,要用(负)优先级作为Less方法的排序来实现Heap接口,因此Push增加项目,而Pop从队列中删除优先级最高的项目。实例中包括这样的实现;文件example_pq_test.go中有完整的源代码。

Example
Example

常量

This section is empty.

变量

This section is empty.

函数

func Fix <- go1.2

1
func Fix(h Interface, i int)

Fix re-establishes the heap ordering after the element at index i has changed its value. Changing the value of the element at index i and then calling Fix is equivalent to, but less expensive than, calling Remove(h, i) followed by a Push of the new value. The complexity is O(log n) where n = h.Len().

Fix在索引i处的元素改变其值后重新建立堆的顺序。改变索引i处元素的值,然后调用Fix,相当于调用Remove(h, i),然后推送新的值,但成本较低。复杂度是O(log n),其中n = h.Len()。

func Init

1
func Init(h Interface)

Init establishes the heap invariants required by the other routines in this package. Init is idempotent with respect to the heap invariants and may be called whenever the heap invariants may have been invalidated. The complexity is O(n) where n = h.Len().

Init建立了本包中其他例程所要求的堆不变性。Init对于堆不变性来说是等价的,只要堆不变性可能已经失效,就可以调用它。复杂度为O(n),其中n = h.Len()。

func Pop

1
func Pop(h Interface) any

Pop removes and returns the minimum element (according to Less) from the heap. The complexity is O(log n) where n = h.Len(). Pop is equivalent to Remove(h, 0).

Pop删除并返回堆中的最小元素(根据Less)。复杂度为O(log n),其中n = h.Len()。Pop等同于Remove(h, 0)。

func Push

1
func Push(h Interface, x any)

Push pushes the element x onto the heap. The complexity is O(log n) where n = h.Len().

Push将元素x推到堆上。复杂度为O(log n),其中n = h.Len()。

func Remove

1
func Remove(h Interface, i int) any

Remove removes and returns the element at index i from the heap. The complexity is O(log n) where n = h.Len().

Remove从堆中删除并返回索引为i的元素。复杂度为O(log n),其中n = h.Len()。

类型

type Interface

1
2
3
4
5
type Interface interface {
	sort.Interface
	Push(x any) // add x as element Len()  //添加x为元素Len()
	Pop() any   // remove and return element Len() - 1.  // 删除并返回元素Len() - 1.
}

The Interface type describes the requirements for a type using the routines in this package. Any type that implements it may be used as a min-heap with the following invariants (established after Init has been called or if the data is empty or sorted):

接口类型描述了一个使用本包中的例程的类型的要求。任何实现它的类型都可以作为最小堆使用,并具有以下不变性(在调用Init后或数据为空或被排序后建立):

!h.Less(j, i) for 0 <= i < h.Len() and 2*i+1 <= j <= 2*i+2 and j < h.Len()

Note that Push and Pop in this interface are for package heap’s implementation to call. To add and remove things from the heap, use heap.Push and heap.Pop.

注意,这个接口中的Push和Pop是供包堆的实现调用的。要从堆中添加和删除东西,请使用heap.Push和heap.Pop。

3.2 - list

list

https://pkg.go.dev/container/list@go1.20.1

Package list implements a doubly linked list.

包list实现了一个双链表。

To iterate over a list (where l is a *List):

要在一个列表上进行迭代(其中l是一个*List):

for e := l.Front(); e != nil; e = e.Next() {
	// do something with e.Value
	//对e.Value做一些处理
}
Example

常量

This section is empty.

变量

This section is empty.

函数

This section is empty.

类型

type Element

1
2
3
4
5
6
7
type Element struct {

	// The value stored with this element.
    // 这个元素存储的值。
	Value any
	// contains filtered or unexported fields
}

Element is an element of a linked list.

Element是链接列表的一个元素。

(*Element) Next

1
func (e *Element) Next() *Element

Next returns the next list element or nil.

Next 返回下一个列表元素或nil。

(*Element) Prev

1
func (e *Element) Prev() *Element

Prev returns the previous list element or nil.

Prev返回前一个列表元素或nil。

type List

1
2
3
type List struct {
	// contains filtered or unexported fields
}

List represents a doubly linked list. The zero value for List is an empty list ready to use.

List表示一个双链表。List的零值是一个准备使用的空列表。

func New

1
func New() *List

New returns an initialized list.

New返回一个初始化的列表。

(*List) Back

1
func (l *List) Back() *Element

Back returns the last element of list l or nil if the list is empty.

Back返回列表l的最后一个元素,如果列表为空,则返回nil。

(*List) Front

1
func (l *List) Front() *Element

Front returns the first element of list l or nil if the list is empty.

Front返回列表l的第一个元素,如果列表为空则返回nil。

(*List) Init

1
func (l *List) Init() *List

Init initializes or clears list l.

Init 初始化或清除列表l。

(*List) InsertAfter

1
func (l *List) InsertAfter(v any, mark *Element) *Element

InsertAfter inserts a new element e with value v immediately after mark and returns e. If mark is not an element of l, the list is not modified. The mark must not be nil.

InsertAfter在mark之后插入一个新的元素e,其值为v,并返回e。如果mark不是l的一个元素,列表不会被修改。mark不能是nil。

(*List) InsertBefore

1
func (l *List) InsertBefore(v any, mark *Element) *Element

InsertBefore inserts a new element e with value v immediately before mark and returns e. If mark is not an element of l, the list is not modified. The mark must not be nil.

InsertBefore在mark之前插入一个新的元素e,其值为v,并返回e,如果mark不是l的一个元素,列表就不会被修改。mark不能是nil。

(*List) Len

1
func (l *List) Len() int

Len returns the number of elements of list l. The complexity is O(1).

Len返回列表l的元素数,其复杂度为O(1)。

(*List) MoveAfter <- go1.2

1
func (l *List) MoveAfter(e, mark *Element)

MoveAfter moves element e to its new position after mark. If e or mark is not an element of l, or e == mark, the list is not modified. The element and mark must not be nil.

MoveAfter将元素e移动到mark之后的新位置。如果e或mark不是l的一个元素,或者e == mark,列表不会被修改。元素和mark不能是nil。

(*List) MoveBefore <- go1.2

1
func (l *List) MoveBefore(e, mark *Element)

MoveBefore moves element e to its new position before mark. If e or mark is not an element of l, or e == mark, the list is not modified. The element and mark must not be nil.

MoveBefore将元素e移动到mark之前的新位置。如果e或mark不是l的一个元素,或者e == mark,列表不会被修改。元素和mark不能是nil。

(*List) MoveToBack

1
func (l *List) MoveToBack(e *Element)

MoveToBack moves element e to the back of list l. If e is not an element of l, the list is not modified. The element must not be nil.

MoveToBack把元素e移到列表l的后面。如果e不是l的一个元素,列表不会被修改。该元素不能是nil。

(*List) MoveToFront

1
func (l *List) MoveToFront(e *Element)

MoveToFront moves element e to the front of list l. If e is not an element of l, the list is not modified. The element must not be nil.

MoveToFront把元素e移到列表l的前面,如果e不是l的元素,列表不被修改。该元素不能是nil。

(*List) PushBack

1
func (l *List) PushBack(v any) *Element

PushBack inserts a new element e with value v at the back of list l and returns e.

PushBack在列表l的后面插入一个新元素e,其值为v,并返回e。

(*List) PushBackList

1
func (l *List) PushBackList(other *List)

PushBackList inserts a copy of another list at the back of list l. The lists l and other may be the same. They must not be nil.

PushBackList在列表l的后面插入一个另一个列表的副本。它们不能是nil。

(*List) PushFront

1
func (l *List) PushFront(v any) *Element

PushFront inserts a new element e with value v at the front of list l and returns e.

PushFront在列表l的前面插入一个值为v的新元素e,并返回e。

(*List) PushFrontList

1
func (l *List) PushFrontList(other *List)

PushFrontList inserts a copy of another list at the front of list l. The lists l and other may be the same. They must not be nil.

PushFrontList在列表l的前面插入一个另一个列表的副本。它们不能是nil。

(*List) Remove

1
func (l *List) Remove(e *Element) any

Remove removes e from l if e is an element of list l. It returns the element value e.Value. The element must not be nil.

如果e是列表l的一个元素,Remove将e从l中移除,并返回元素值e.Value。该元素不能是nil。

3.3 - ring

ring

https://pkg.go.dev/container/ring@go1.20.1

Package ring implements operations on circular lists.

ring 包实现了对循环列表的操作。

常量

This section is empty.

变量

This section is empty.

函数

This section is empty.

类型

type Ring

1
2
3
4
type Ring struct {
	Value any // for use by client; untouched by this library// 供客户端使用;本库不触及。
	// contains filtered or unexported fields
}

A Ring is an element of a circular list, or ring. Rings do not have a beginning or end; a pointer to any ring element serves as reference to the entire ring. Empty rings are represented as nil Ring pointers. The zero value for a Ring is a one-element ring with a nil Value.

Ring是一个循环列表的一个元素,或者说是环。环没有开始或结束;任何环元素的指针都可以作为整个环的参考。空的环表示为nil Ring指针。一个环的零值是一个具有nil值的单元素环。

func New

1
func New(n int) *Ring

New creates a ring of n elements.

New创建一个有n个元素的环。

(*Ring) Do

1
func (r *Ring) Do(f func(any))

Do calls function f on each element of the ring, in forward order. The behavior of Do is undefined if f changes *r.

Do在环的每个元素上以正向顺序调用函数f。如果f改变了*r,Do的行为是未定义的。

Example

(*Ring) Len

1
func (r *Ring) Len() int

Len computes the number of elements in ring r. It executes in time proportional to the number of elements.

Len计算环中元素的数量,执行时间与元素的数量成正比。

Example

(*Ring) Link

1
func (r *Ring) Link(s *Ring) *Ring

Link connects ring r with ring s such that r.Next() becomes s and returns the original value for r.Next(). r must not be empty.

Link将r环和s环连接起来,这样r.Next()就变成了s,并返回r.Next()的原始值,r不能为空。

If r and s point to the same ring, linking them removes the elements between r and s from the ring. The removed elements form a subring and the result is a reference to that subring (if no elements were removed, the result is still the original value for r.Next(), and not nil).

如果r和s指向同一个环,连接它们会从环中移除r和s之间的元素。被移除的元素形成一个子环,结果是对该子环的引用(如果没有元素被移除,结果仍然是r.Next()的原始值,而不是nil)。

If r and s point to different rings, linking them creates a single ring with the elements of s inserted after r. The result points to the element following the last element of s after insertion.

如果r和s指向不同的环,连接它们会创建一个单一的环,其中s的元素插入到r之后。

Example

(*Ring) Move

1
func (r *Ring) Move(n int) *Ring

Move moves n % r.Len() elements backward (n < 0) or forward (n >= 0) in the ring and returns that ring element. r must not be empty.

Move在环中向后(n < 0)或向前(n >= 0)移动n % r.Len()元素,并返回该环元素。

Example

(*Ring) Next

1
func (r *Ring) Next() *Ring

Next returns the next ring element. r must not be empty.

Next 返回下一个环状元素,r必须不是空的。

Example

(*Ring) Prev

1
func (r *Ring) Prev() *Ring

Prev returns the previous ring element. r must not be empty.

Prev返回上一个环状元素,r不能为空。

Example

(*Ring) Unlink

1
func (r *Ring) Unlink(n int) *Ring

Unlink removes n % r.Len() elements from the ring r, starting at r.Next(). If n % r.Len() == 0, r remains unchanged. The result is the removed subring. r must not be empty.

Unlink从r环中移除n % r.Len()元素,从r.Next()开始。如果n % r.Len() == 0,r保持不变。结果是移除的子环。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package main

import (
	"container/ring"
	"fmt"
)

func main() {
	// Create a new ring of size 6
	r := ring.New(6)

	// Get the length of the ring
	n := r.Len()

	// Initialize the ring with some integer values
	for i := 0; i < n; i++ {
		r.Value = i
		r = r.Next()
	}

	// Unlink three elements from r, starting from r.Next()
	r.Unlink(3)

	// Iterate through the remaining ring and print its contents
	r.Do(func(p any) {
		fmt.Println(p.(int))
	})

}
Output:

0
4
5

4 - crypto

4.1 - aes

aes

https://pkg.go.dev/crypto/aes@go1.20.1

Package aes implements AES encryption (formerly Rijndael), as defined in U.S. Federal Information Processing Standards Publication 197.

The AES operations in this package are not implemented using constant-time algorithms. An exception is when running on systems with enabled hardware support for AES that makes these operations constant-time. Examples include amd64 systems using AES-NI extensions and s390x systems using Message-Security-Assist extensions. On such systems, when the result of NewCipher is passed to cipher.NewGCM, the GHASH operation used by GCM is also constant-time.

常量

View Source

const BlockSize = 16

The AES block size in bytes.

变量

This section is empty.

函数

func NewCipher

func NewCipher(key []byte) (cipher.Block, error)

NewCipher creates and returns a new cipher.Block. The key argument should be the AES key, either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256.

类型

type KeySizeError

type KeySizeError int

(KeySizeError) Error

func (k KeySizeError) Error() string

4.2 - cipher

cipher

https://pkg.go.dev/crypto/cipher@go1.20.1

Package cipher implements standard block cipher modes that can be wrapped around low-level block cipher implementations. See https://csrc.nist.gov/groups/ST/toolkit/BCM/current_modes.html and NIST Special Publication 800-38A.

常量

This section is empty.

变量

This section is empty.

函数

This section is empty.

类型

type AEAD added in go1.2

type AEAD interface {
	// NonceSize returns the size of the nonce that must be passed to Seal
	// and Open.
	NonceSize() int

	// Overhead returns the maximum difference between the lengths of a
	// plaintext and its ciphertext.
	Overhead() int

	// Seal encrypts and authenticates plaintext, authenticates the
	// additional data and appends the result to dst, returning the updated
	// slice. The nonce must be NonceSize() bytes long and unique for all
	// time, for a given key.
	//
	// To reuse plaintext's storage for the encrypted output, use plaintext[:0]
	// as dst. Otherwise, the remaining capacity of dst must not overlap plaintext.
	Seal(dst, nonce, plaintext, additionalData []byte) []byte

	// Open decrypts and authenticates ciphertext, authenticates the
	// additional data and, if successful, appends the resulting plaintext
	// to dst, returning the updated slice. The nonce must be NonceSize()
	// bytes long and both it and the additional data must match the
	// value passed to Seal.
	//
	// To reuse ciphertext's storage for the decrypted output, use ciphertext[:0]
	// as dst. Otherwise, the remaining capacity of dst must not overlap plaintext.
	//
	// Even if the function fails, the contents of dst, up to its capacity,
	// may be overwritten.
	Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error)
}

AEAD is a cipher mode providing authenticated encryption with associated data. For a description of the methodology, see https://en.wikipedia.org/wiki/Authenticated_encryption.

func NewGCM added in go1.2

func NewGCM(cipher Block) (AEAD, error)

NewGCM returns the given 128-bit, block cipher wrapped in Galois Counter Mode with the standard nonce length.

In general, the GHASH operation performed by this implementation of GCM is not constant-time. An exception is when the underlying Block was created by aes.NewCipher on systems with hardware support for AES. See the crypto/aes package documentation for details.

Example (Decrypt) 
Example (Encrypt) 

func NewGCMWithNonceSize added in go1.5

func NewGCMWithNonceSize(cipher Block, size int) (AEAD, error)

NewGCMWithNonceSize returns the given 128-bit, block cipher wrapped in Galois Counter Mode, which accepts nonces of the given length. The length must not be zero.

Only use this function if you require compatibility with an existing cryptosystem that uses non-standard nonce lengths. All other users should use NewGCM, which is faster and more resistant to misuse.

func NewGCMWithTagSize added in go1.11

func NewGCMWithTagSize(cipher Block, tagSize int) (AEAD, error)

NewGCMWithTagSize returns the given 128-bit, block cipher wrapped in Galois Counter Mode, which generates tags with the given length.

Tag sizes between 12 and 16 bytes are allowed.

Only use this function if you require compatibility with an existing cryptosystem that uses non-standard tag lengths. All other users should use NewGCM, which is more resistant to misuse.

type Block

type Block interface {
	// BlockSize returns the cipher's block size.
	BlockSize() int

	// Encrypt encrypts the first block in src into dst.
	// Dst and src must overlap entirely or not at all.
	Encrypt(dst, src []byte)

	// Decrypt decrypts the first block in src into dst.
	// Dst and src must overlap entirely or not at all.
	Decrypt(dst, src []byte)
}

A Block represents an implementation of block cipher using a given key. It provides the capability to encrypt or decrypt individual blocks. The mode implementations extend that capability to streams of blocks.

type BlockMode

type BlockMode interface {
	// BlockSize returns the mode's block size.
	BlockSize() int

	// CryptBlocks encrypts or decrypts a number of blocks. The length of
	// src must be a multiple of the block size. Dst and src must overlap
	// entirely or not at all.
	//
	// If len(dst) < len(src), CryptBlocks should panic. It is acceptable
	// to pass a dst bigger than src, and in that case, CryptBlocks will
	// only update dst[:len(src)] and will not touch the rest of dst.
	//
	// Multiple calls to CryptBlocks behave as if the concatenation of
	// the src buffers was passed in a single run. That is, BlockMode
	// maintains state and does not reset at each CryptBlocks call.
	CryptBlocks(dst, src []byte)
}

A BlockMode represents a block cipher running in a block-based mode (CBC, ECB etc).

func NewCBCDecrypter

func NewCBCDecrypter(b Block, iv []byte) BlockMode

NewCBCDecrypter returns a BlockMode which decrypts in cipher block chaining mode, using the given Block. The length of iv must be the same as the Block’s block size and must match the iv used to encrypt the data.

Example 

func NewCBCEncrypter

func NewCBCEncrypter(b Block, iv []byte) BlockMode

NewCBCEncrypter returns a BlockMode which encrypts in cipher block chaining mode, using the given Block. The length of iv must be the same as the Block’s block size.

Example 

type Stream

type Stream interface {
	// XORKeyStream XORs each byte in the given slice with a byte from the
	// cipher's key stream. Dst and src must overlap entirely or not at all.
	//
	// If len(dst) < len(src), XORKeyStream should panic. It is acceptable
	// to pass a dst bigger than src, and in that case, XORKeyStream will
	// only update dst[:len(src)] and will not touch the rest of dst.
	//
	// Multiple calls to XORKeyStream behave as if the concatenation of
	// the src buffers was passed in a single run. That is, Stream
	// maintains state and does not reset at each XORKeyStream call.
	XORKeyStream(dst, src []byte)
}

A Stream represents a stream cipher.

func NewCFBDecrypter

func NewCFBDecrypter(block Block, iv []byte) Stream

NewCFBDecrypter returns a Stream which decrypts with cipher feedback mode, using the given Block. The iv must be the same length as the Block’s block size.

Example 

func NewCFBEncrypter

func NewCFBEncrypter(block Block, iv []byte) Stream

NewCFBEncrypter returns a Stream which encrypts with cipher feedback mode, using the given Block. The iv must be the same length as the Block’s block size.

Example 

func NewCTR

func NewCTR(block Block, iv []byte) Stream

NewCTR returns a Stream which encrypts/decrypts using the given Block in counter mode. The length of iv must be the same as the Block’s block size.

Example 

func NewOFB

func NewOFB(b Block, iv []byte) Stream

NewOFB returns a Stream that encrypts or decrypts using the block cipher b in output feedback mode. The initialization vector iv’s length must be equal to b’s block size.

Example 

type StreamReader

type StreamReader struct {
	S Stream
	R io.Reader
}

StreamReader wraps a Stream into an io.Reader. It calls XORKeyStream to process each slice of data which passes through.

Example 

(StreamReader) Read

func (r StreamReader) Read(dst []byte) (n int, err error)

type StreamWriter

type StreamWriter struct {
	S   Stream
	W   io.Writer
	Err error // unused
}

StreamWriter wraps a Stream into an io.Writer. It calls XORKeyStream to process each slice of data which passes through. If any Write call returns short then the StreamWriter is out of sync and must be discarded. A StreamWriter has no internal buffering; Close does not need to be called to flush write data.

Example 

(StreamWriter) Close

func (w StreamWriter) Close() error

Close closes the underlying Writer and returns its Close return value, if the Writer is also an io.Closer. Otherwise it returns nil.

(StreamWriter) Write

func (w StreamWriter) Write(src []byte) (n int, err error)

4.3 - crypto

crypto

https://pkg.go.dev/crypto@go1.20.1

Package crypto collects common cryptographic constants.

常量

This section is empty.

变量

This section is empty.

函数

func RegisterHash

func RegisterHash(h Hash, f func() hash.Hash)

RegisterHash registers a function that returns a new instance of the given hash function. This is intended to be called from the init function in packages that implement hash functions.

类型

type Decrypter added in go1.5

type Decrypter interface {
	// Public returns the public key corresponding to the opaque,
	// private key.
	Public() PublicKey

	// Decrypt decrypts msg. The opts argument should be appropriate for
	// the primitive used. See the documentation in each implementation for
	// details.
	Decrypt(rand io.Reader, msg []byte, opts DecrypterOpts) (plaintext []byte, err error)
}

Decrypter is an interface for an opaque private key that can be used for asymmetric decryption operations. An example would be an RSA key kept in a hardware module.

type DecrypterOpts added in go1.5

type DecrypterOpts any

type Hash

type Hash uint

Hash identifies a cryptographic hash function that is implemented in another package.

const (
	MD4         Hash = 1 + iota // import golang.org/x/crypto/md4
	MD5                         // import crypto/md5
	SHA1                        // import crypto/sha1
	SHA224                      // import crypto/sha256
	SHA256                      // import crypto/sha256
	SHA384                      // import crypto/sha512
	SHA512                      // import crypto/sha512
	MD5SHA1                     // no implementation; MD5+SHA1 used for TLS RSA
	RIPEMD160                   // import golang.org/x/crypto/ripemd160
	SHA3_224                    // import golang.org/x/crypto/sha3
	SHA3_256                    // import golang.org/x/crypto/sha3
	SHA3_384                    // import golang.org/x/crypto/sha3
	SHA3_512                    // import golang.org/x/crypto/sha3
	SHA512_224                  // import crypto/sha512
	SHA512_256                  // import crypto/sha512
	BLAKE2s_256                 // import golang.org/x/crypto/blake2s
	BLAKE2b_256                 // import golang.org/x/crypto/blake2b
	BLAKE2b_384                 // import golang.org/x/crypto/blake2b
	BLAKE2b_512                 // import golang.org/x/crypto/blake2b

)

(Hash) Available

func (h Hash) Available() bool

Available reports whether the given hash function is linked into the binary.

(Hash) HashFunc added in go1.4

func (h Hash) HashFunc() Hash

HashFunc simply returns the value of h so that Hash implements SignerOpts.

(Hash) New

func (h Hash) New() hash.Hash

New returns a new hash.Hash calculating the given hash function. New panics if the hash function is not linked into the binary.

(Hash) Size

func (h Hash) Size() int

Size returns the length, in bytes, of a digest resulting from the given hash function. It doesn’t require that the hash function in question be linked into the program.

(Hash) String added in go1.15

func (h Hash) String() string

type PrivateKey

type PrivateKey any

PrivateKey represents a private key using an unspecified algorithm.

Although this type is an empty interface for backwards compatibility reasons, all private key types in the standard library implement the following interface

interface{
    Public() crypto.PublicKey
    Equal(x crypto.PrivateKey) bool
}

as well as purpose-specific interfaces such as Signer and Decrypter, which can be used for increased type safety within applications.

type PublicKey added in go1.2

type PublicKey any

PublicKey represents a public key using an unspecified algorithm.

Although this type is an empty interface for backwards compatibility reasons, all public key types in the standard library implement the following interface

interface{
    Equal(x crypto.PublicKey) bool
}

which can be used for increased type safety within applications.

type Signer added in go1.4

type Signer interface {
	// Public returns the public key corresponding to the opaque,
	// private key.
	Public() PublicKey

	// Sign signs digest with the private key, possibly using entropy from
	// rand. For an RSA key, the resulting signature should be either a
	// PKCS #1 v1.5 or PSS signature (as indicated by opts). For an (EC)DSA
	// key, it should be a DER-serialised, ASN.1 signature structure.
	//
	// Hash implements the SignerOpts interface and, in most cases, one can
	// simply pass in the hash function used as opts. Sign may also attempt
	// to type assert opts to other types in order to obtain algorithm
	// specific values. See the documentation in each package for details.
	//
	// Note that when a signature of a hash of a larger message is needed,
	// the caller is responsible for hashing the larger message and passing
	// the hash (as digest) and the hash function (as opts) to Sign.
	Sign(rand io.Reader, digest []byte, opts SignerOpts) (signature []byte, err error)
}

Signer is an interface for an opaque private key that can be used for signing operations. For example, an RSA key kept in a hardware module.

type SignerOpts added in go1.4

type SignerOpts interface {
	// HashFunc returns an identifier for the hash function used to produce
	// the message passed to Signer.Sign, or else zero to indicate that no
	// hashing was done.
	HashFunc() Hash
}

SignerOpts contains options for signing with a Signer.

4.4 - des

des

Package des implements the Data Encryption Standard (DES) and the Triple Data Encryption Algorithm (TDEA) as defined in U.S. Federal Information Processing Standards Publication 46-3.

DES is cryptographically broken and should not be used for secure applications.

常量

View Source

const BlockSize = 8

The DES block size in bytes.

变量

This section is empty.

函数

func NewCipher

func NewCipher(key []byte) (cipher.Block, error)

NewCipher creates and returns a new cipher.Block.

func NewTripleDESCipher

func NewTripleDESCipher(key []byte) (cipher.Block, error)

NewTripleDESCipher creates and returns a new cipher.Block.

Example 

类型

type KeySizeError

type KeySizeError int

(KeySizeError) Error

func (k KeySizeError) Error() string

4.5 - dsa

dsa

https://pkg.go.dev/crypto/dsa@go1.20.1

Package dsa implements the Digital Signature Algorithm, as defined in FIPS 186-3.

The DSA operations in this package are not implemented using constant-time algorithms.

Deprecated: DSA is a legacy algorithm, and modern alternatives such as Ed25519 (implemented by package crypto/ed25519) should be used instead. Keys with 1024-bit moduli (L1024N160 parameters) are cryptographically weak, while bigger keys are not widely supported. Note that FIPS 186-5 no longer approves DSA for signature generation.

常量

This section is empty.

变量

View Source

var ErrInvalidPublicKey = errors.New("crypto/dsa: invalid public key")

ErrInvalidPublicKey results when a public key is not usable by this code. FIPS is quite strict about the format of DSA keys, but other code may be less so. Thus, when using keys which may have been generated by other code, this error must be handled.

函数

func GenerateKey

func GenerateKey(priv *PrivateKey, rand io.Reader) error

GenerateKey generates a public&private key pair. The Parameters of the PrivateKey must already be valid (see GenerateParameters).

func GenerateParameters

func GenerateParameters(params *Parameters, rand io.Reader, sizes ParameterSizes) error

GenerateParameters puts a random, valid set of DSA parameters into params. This function can take many seconds, even on fast machines.

func Sign

func Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err error)

Sign signs an arbitrary length hash (which should be the result of hashing a larger message) using the private key, priv. It returns the signature as a pair of integers. The security of the private key depends on the entropy of rand.

Note that FIPS 186-3 section 4.6 specifies that the hash should be truncated to the byte-length of the subgroup. This function does not perform that truncation itself.

Be aware that calling Sign with an attacker-controlled PrivateKey may require an arbitrary amount of CPU.

func Verify

func Verify(pub *PublicKey, hash []byte, r, s *big.Int) bool

Verify verifies the signature in r, s of hash using the public key, pub. It reports whether the signature is valid.

Note that FIPS 186-3 section 4.6 specifies that the hash should be truncated to the byte-length of the subgroup. This function does not perform that truncation itself.

类型

type ParameterSizes

type ParameterSizes int

ParameterSizes is an enumeration of the acceptable bit lengths of the primes in a set of DSA parameters. See FIPS 186-3, section 4.2.

const (
	L1024N160 ParameterSizes = iota
	L2048N224
	L2048N256
	L3072N256
)

type Parameters

type Parameters struct {
	P, Q, G *big.Int
}

Parameters represents the domain parameters for a key. These parameters can be shared across many keys. The bit length of Q must be a multiple of 8.

type PrivateKey

type PrivateKey struct {
	PublicKey
	X *big.Int
}

PrivateKey represents a DSA private key.

type PublicKey

type PublicKey struct {
	Parameters
	Y *big.Int
}

PublicKey represents a DSA public key.

4.6 - ecdh

ecdh

https://pkg.go.dev/crypto/ecdh@go1.20.1

Package ecdh implements Elliptic Curve Diffie-Hellman over NIST curves and Curve25519.

常量

This section is empty.

变量

This section is empty.

函数

This section is empty.

类型

type Curve

type Curve interface {
	// GenerateKey generates a new PrivateKey from rand.
	GenerateKey(rand io.Reader) (*PrivateKey, error)

	// NewPrivateKey checks that key is valid and returns a PrivateKey.
	//
	// For NIST curves, this follows SEC 1, Version 2.0, Section 2.3.6, which
	// amounts to decoding the bytes as a fixed length big endian integer and
	// checking that the result is lower than the order of the curve. The zero
	// private key is also rejected, as the encoding of the corresponding public
	// key would be irregular.
	//
	// For X25519, this only checks the scalar length.
	NewPrivateKey(key []byte) (*PrivateKey, error)

	// NewPublicKey checks that key is valid and returns a PublicKey.
	//
	// For NIST curves, this decodes an uncompressed point according to SEC 1,
	// Version 2.0, Section 2.3.4. Compressed encodings and the point at
	// infinity are rejected.
	//
	// For X25519, this only checks the u-coordinate length. Adversarially
	// selected public keys can cause ECDH to return an error.
	NewPublicKey(key []byte) (*PublicKey, error)
	// contains filtered or unexported methods
}

func P256

func P256() Curve

P256 returns a Curve which implements NIST P-256 (FIPS 186-3, section D.2.3), also known as secp256r1 or prime256v1.

Multiple invocations of this function will return the same value, which can be used for equality checks and switch statements.

func P384

func P384() Curve

P384 returns a Curve which implements NIST P-384 (FIPS 186-3, section D.2.4), also known as secp384r1.

Multiple invocations of this function will return the same value, which can be used for equality checks and switch statements.

func P521

func P521() Curve

P521 returns a Curve which implements NIST P-521 (FIPS 186-3, section D.2.5), also known as secp521r1.

Multiple invocations of this function will return the same value, which can be used for equality checks and switch statements.

func X25519

func X25519() Curve

X25519 returns a Curve which implements the X25519 function over Curve25519 (RFC 7748, Section 5).

Multiple invocations of this function will return the same value, so it can be used for equality checks and switch statements.

type PrivateKey

type PrivateKey struct {
	// contains filtered or unexported fields
}

PrivateKey is an ECDH private key, usually kept secret.

These keys can be parsed with crypto/x509.ParsePKCS8PrivateKey and encoded with crypto/x509.MarshalPKCS8PrivateKey. For NIST curves, they then need to be converted with crypto/ecdsa.PrivateKey.ECDH after parsing.

(*PrivateKey) Bytes

func (k *PrivateKey) Bytes() []byte

Bytes returns a copy of the encoding of the private key.

(*PrivateKey) Curve

func (k *PrivateKey) Curve() Curve

(*PrivateKey) ECDH

func (k *PrivateKey) ECDH(remote *PublicKey) ([]byte, error)

ECDH performs a ECDH exchange and returns the shared secret.

For NIST curves, this performs ECDH as specified in SEC 1, Version 2.0, Section 3.3.1, and returns the x-coordinate encoded according to SEC 1, Version 2.0, Section 2.3.5. The result is never the point at infinity.

For X25519, this performs ECDH as specified in RFC 7748, Section 6.1. If the result is the all-zero value, ECDH returns an error.

(*PrivateKey) Equal

func (k *PrivateKey) Equal(x crypto.PrivateKey) bool

Equal returns whether x represents the same private key as k.

Note that there can be equivalent private keys with different encodings which would return false from this check but behave the same way as inputs to ECDH.

This check is performed in constant time as long as the key types and their curve match.

(*PrivateKey) Public

func (k *PrivateKey) Public() crypto.PublicKey

Public implements the implicit interface of all standard library private keys. See the docs of crypto.PrivateKey.

(*PrivateKey) PublicKey

func (k *PrivateKey) PublicKey() *PublicKey

type PublicKey

type PublicKey struct {
	// contains filtered or unexported fields
}

PublicKey is an ECDH public key, usually a peer’s ECDH share sent over the wire.

These keys can be parsed with crypto/x509.ParsePKIXPublicKey and encoded with crypto/x509.MarshalPKIXPublicKey. For NIST curves, they then need to be converted with crypto/ecdsa.PublicKey.ECDH after parsing.

(*PublicKey) Bytes

func (k *PublicKey) Bytes() []byte

Bytes returns a copy of the encoding of the public key.

(*PublicKey) Curve

func (k *PublicKey) Curve() Curve

(*PublicKey) Equal

func (k *PublicKey) Equal(x crypto.PublicKey) bool

Equal returns whether x represents the same public key as k.

Note that there can be equivalent public keys with different encodings which would return false from this check but behave the same way as inputs to ECDH.

This check is performed in constant time as long as the key types and their curve match.

4.7 - ecdsa

ecdsa

https://pkg.go.dev/crypto/ecdsa@go1.20.1

Package ecdsa implements the Elliptic Curve Digital Signature Algorithm, as defined in FIPS 186-4 and SEC 1, Version 2.0.

Signatures generated by this package are not deterministic, but entropy is mixed with the private key and the message, achieving the same level of security in case of randomness source failure.

Example 

常量

This section is empty.

变量

This section is empty.

函数

func Sign

func Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err error)

Sign signs a hash (which should be the result of hashing a larger message) using the private key, priv. If the hash is longer than the bit-length of the private key’s curve order, the hash will be truncated to that length. It returns the signature as a pair of integers. Most applications should use SignASN1 instead of dealing directly with r, s.

func SignASN1 added in go1.15

func SignASN1(rand io.Reader, priv *PrivateKey, hash []byte) ([]byte, error)

SignASN1 signs a hash (which should be the result of hashing a larger message) using the private key, priv. If the hash is longer than the bit-length of the private key’s curve order, the hash will be truncated to that length. It returns the ASN.1 encoded signature.

func Verify

func Verify(pub *PublicKey, hash []byte, r, s *big.Int) bool

Verify verifies the signature in r, s of hash using the public key, pub. Its return value records whether the signature is valid. Most applications should use VerifyASN1 instead of dealing directly with r, s.

func VerifyASN1 added in go1.15

func VerifyASN1(pub *PublicKey, hash, sig []byte) bool

VerifyASN1 verifies the ASN.1 encoded signature, sig, of hash using the public key, pub. Its return value records whether the signature is valid.

类型

type PrivateKey

type PrivateKey struct {
	PublicKey
	D *big.Int
}

PrivateKey represents an ECDSA private key.

func GenerateKey

func GenerateKey(c elliptic.Curve, rand io.Reader) (*PrivateKey, error)

GenerateKey generates a public and private key pair.

(*PrivateKey) ECDH added in go1.20

func (k *PrivateKey) ECDH() (*ecdh.PrivateKey, error)

ECDH returns k as a ecdh.PrivateKey. It returns an error if the key is invalid according to the definition of ecdh.Curve.NewPrivateKey, or if the Curve is not supported by crypto/ecdh.

(*PrivateKey) Equal added in go1.15

func (priv *PrivateKey) Equal(x crypto.PrivateKey) bool

Equal reports whether priv and x have the same value.

See PublicKey.Equal for details on how Curve is compared.

(*PrivateKey) Public added in go1.4

func (priv *PrivateKey) Public() crypto.PublicKey

Public returns the public key corresponding to priv.

(*PrivateKey) Sign added in go1.4

func (priv *PrivateKey) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error)

Sign signs digest with priv, reading randomness from rand. The opts argument is not currently used but, in keeping with the crypto.Signer interface, should be the hash function used to digest the message.

This method implements crypto.Signer, which is an interface to support keys where the private part is kept in, for example, a hardware module. Common uses can use the SignASN1 function in this package directly.

type PublicKey

type PublicKey struct {
	elliptic.Curve
	X, Y *big.Int
}

PublicKey represents an ECDSA public key.

(*PublicKey) ECDH added in go1.20

func (k *PublicKey) ECDH() (*ecdh.PublicKey, error)

ECDH returns k as a ecdh.PublicKey. It returns an error if the key is invalid according to the definition of ecdh.Curve.NewPublicKey, or if the Curve is not supported by crypto/ecdh.

(*PublicKey) Equal added in go1.15

func (pub *PublicKey) Equal(x crypto.PublicKey) bool

Equal reports whether pub and x have the same value.

Two keys are only considered to have the same value if they have the same Curve value. Note that for example elliptic.P256() and elliptic.P256().Params() are different values, as the latter is a generic not constant time implementation.

4.8 - ed25519

ed25519

https://pkg.go.dev/crypto/ed25519@go1.20.1

Package ed25519 implements the Ed25519 signature algorithm. See https://ed25519.cr.yp.to/.

These functions are also compatible with the “Ed25519” function defined in RFC 8032. However, unlike RFC 8032’s formulation, this package’s private key representation includes a public key suffix to make multiple signing operations with the same key more efficient. This package refers to the RFC 8032 private key as the “seed”.

Example (Ed25519ctx) 

常量

View Source

const (
	// PublicKeySize is the size, in bytes, of public keys as used in this package.
	PublicKeySize = 32
	// PrivateKeySize is the size, in bytes, of private keys as used in this package.
	PrivateKeySize = 64
	// SignatureSize is the size, in bytes, of signatures generated and verified by this package.
	SignatureSize = 64
	// SeedSize is the size, in bytes, of private key seeds. These are the private key representations used by RFC 8032.
	SeedSize = 32
)

变量

This section is empty.

函数

func GenerateKey

func GenerateKey(rand io.Reader) (PublicKey, PrivateKey, error)

GenerateKey generates a public/private key pair using entropy from rand. If rand is nil, crypto/rand.Reader will be used.

func Sign

func Sign(privateKey PrivateKey, message []byte) []byte

Sign signs the message with privateKey and returns a signature. It will panic if len(privateKey) is not PrivateKeySize.

func Verify

func Verify(publicKey PublicKey, message, sig []byte) bool

Verify reports whether sig is a valid signature of message by publicKey. It will panic if len(publicKey) is not PublicKeySize.

func VerifyWithOptions added in go1.20

func VerifyWithOptions(publicKey PublicKey, message, sig []byte, opts *Options) error

VerifyWithOptions reports whether sig is a valid signature of message by publicKey. A valid signature is indicated by returning a nil error. It will panic if len(publicKey) is not PublicKeySize.

If opts.Hash is crypto.SHA512, the pre-hashed variant Ed25519ph is used and message is expected to be a SHA-512 hash, otherwise opts.Hash must be crypto.Hash(0) and the message must not be hashed, as Ed25519 performs two passes over messages to be signed.

类型

type Options added in go1.20

type Options struct {
	// Hash can be zero for regular Ed25519, or crypto.SHA512 for Ed25519ph.
	Hash crypto.Hash

	// Context, if not empty, selects Ed25519ctx or provides the context string
	// for Ed25519ph. It can be at most 255 bytes in length.
	Context string
}

Options can be used with PrivateKey.Sign or VerifyWithOptions to select Ed25519 variants.

(*Options) HashFunc added in go1.20

func (o *Options) HashFunc() crypto.Hash

HashFunc returns o.Hash.

type PrivateKey

type PrivateKey []byte

PrivateKey is the type of Ed25519 private keys. It implements crypto.Signer.

func NewKeyFromSeed

func NewKeyFromSeed(seed []byte) PrivateKey

NewKeyFromSeed calculates a private key from a seed. It will panic if len(seed) is not SeedSize. This function is provided for interoperability with RFC 8032. RFC 8032’s private keys correspond to seeds in this package.

(PrivateKey) Equal added in go1.15

func (priv PrivateKey) Equal(x crypto.PrivateKey) bool

Equal reports whether priv and x have the same value.

(PrivateKey) Public

func (priv PrivateKey) Public() crypto.PublicKey

Public returns the PublicKey corresponding to priv.

(PrivateKey) Seed

func (priv PrivateKey) Seed() []byte

Seed returns the private key seed corresponding to priv. It is provided for interoperability with RFC 8032. RFC 8032’s private keys correspond to seeds in this package.

(PrivateKey) Sign

func (priv PrivateKey) Sign(rand io.Reader, message []byte, opts crypto.SignerOpts) (signature []byte, err error)

Sign signs the given message with priv. rand is ignored.

If opts.HashFunc() is crypto.SHA512, the pre-hashed variant Ed25519ph is used and message is expected to be a SHA-512 hash, otherwise opts.HashFunc() must be crypto.Hash(0) and the message must not be hashed, as Ed25519 performs two passes over messages to be signed.

A value of type Options can be used as opts, or crypto.Hash(0) or crypto.SHA512 directly to select plain Ed25519 or Ed25519ph, respectively.

type PublicKey

type PublicKey []byte

PublicKey is the type of Ed25519 public keys.

(PublicKey) Equal added in go1.15

func (pub PublicKey) Equal(x crypto.PublicKey) bool

Equal reports whether pub and x have the same value.

4.9 - elliptic

elliptic

https://pkg.go.dev/crypto/elliptic@go1.20.1

Package elliptic implements the standard NIST P-224, P-256, P-384, and P-521 elliptic curves over prime fields.

The P224(), P256(), P384() and P521() values are necessary to use the crypto/ecdsa package. Most other uses should migrate to the more efficient and safer crypto/ecdh package.

常量

This section is empty.

变量

This section is empty.

函数

func GenerateKey

func GenerateKey(curve Curve, rand io.Reader) (priv []byte, x, y *big.Int, err error)

GenerateKey returns a public/private key pair. The private key is generated using the given reader, which must return random data.

Note: for ECDH, use the GenerateKey methods of the crypto/ecdh package; for ECDSA, use the GenerateKey function of the crypto/ecdsa package.

func Marshal

func Marshal(curve Curve, x, y *big.Int) []byte

Marshal converts a point on the curve into the uncompressed form specified in SEC 1, Version 2.0, Section 2.3.3. If the point is not on the curve (or is the conventional point at infinity), the behavior is undefined.

Note: for ECDH, use the crypto/ecdh package. This function returns an encoding equivalent to that of PublicKey.Bytes in crypto/ecdh.

func MarshalCompressed added in go1.15

func MarshalCompressed(curve Curve, x, y *big.Int) []byte

MarshalCompressed converts a point on the curve into the compressed form specified in SEC 1, Version 2.0, Section 2.3.3. If the point is not on the curve (or is the conventional point at infinity), the behavior is undefined.

func Unmarshal

func Unmarshal(curve Curve, data []byte) (x, y *big.Int)

Unmarshal converts a point, serialized by Marshal, into an x, y pair. It is an error if the point is not in uncompressed form, is not on the curve, or is the point at infinity. On error, x = nil.

Note: for ECDH, use the crypto/ecdh package. This function accepts an encoding equivalent to that of the NewPublicKey methods in crypto/ecdh.

func UnmarshalCompressed added in go1.15

func UnmarshalCompressed(curve Curve, data []byte) (x, y *big.Int)

UnmarshalCompressed converts a point, serialized by MarshalCompressed, into an x, y pair. It is an error if the point is not in compressed form, is not on the curve, or is the point at infinity. On error, x = nil.

类型

type Curve

type Curve interface {
	// Params returns the parameters for the curve.
	Params() *CurveParams

	// IsOnCurve reports whether the given (x,y) lies on the curve.
	//
	// Note: this is a low-level unsafe API. For ECDH, use the crypto/ecdh
	// package. The NewPublicKey methods of NIST curves in crypto/ecdh accept
	// the same encoding as the Unmarshal function, and perform on-curve checks.
	IsOnCurve(x, y *big.Int) bool

	// Add returns the sum of (x1,y1) and (x2,y2).
	//
	// Note: this is a low-level unsafe API.
	Add(x1, y1, x2, y2 *big.Int) (x, y *big.Int)

	// Double returns 2*(x,y).
	//
	// Note: this is a low-level unsafe API.
	Double(x1, y1 *big.Int) (x, y *big.Int)

	// ScalarMult returns k*(x,y) where k is an integer in big-endian form.
	//
	// Note: this is a low-level unsafe API. For ECDH, use the crypto/ecdh
	// package. Most uses of ScalarMult can be replaced by a call to the ECDH
	// methods of NIST curves in crypto/ecdh.
	ScalarMult(x1, y1 *big.Int, k []byte) (x, y *big.Int)

	// ScalarBaseMult returns k*G, where G is the base point of the group
	// and k is an integer in big-endian form.
	//
	// Note: this is a low-level unsafe API. For ECDH, use the crypto/ecdh
	// package. Most uses of ScalarBaseMult can be replaced by a call to the
	// PrivateKey.PublicKey method in crypto/ecdh.
	ScalarBaseMult(k []byte) (x, y *big.Int)
}

A Curve represents a short-form Weierstrass curve with a=-3.

The behavior of Add, Double, and ScalarMult when the input is not a point on the curve is undefined.

Note that the conventional point at infinity (0, 0) is not considered on the curve, although it can be returned by Add, Double, ScalarMult, or ScalarBaseMult (but not the Unmarshal or UnmarshalCompressed functions).

func P224

func P224() Curve

P224 returns a Curve which implements NIST P-224 (FIPS 186-3, section D.2.2), also known as secp224r1. The CurveParams.Name of this Curve is “P-224”.

Multiple invocations of this function will return the same value, so it can be used for equality checks and switch statements.

The cryptographic operations are implemented using constant-time algorithms.

func P256

func P256() Curve

P256 returns a Curve which implements NIST P-256 (FIPS 186-3, section D.2.3), also known as secp256r1 or prime256v1. The CurveParams.Name of this Curve is “P-256”.

Multiple invocations of this function will return the same value, so it can be used for equality checks and switch statements.

The cryptographic operations are implemented using constant-time algorithms.

func P384

func P384() Curve

P384 returns a Curve which implements NIST P-384 (FIPS 186-3, section D.2.4), also known as secp384r1. The CurveParams.Name of this Curve is “P-384”.

Multiple invocations of this function will return the same value, so it can be used for equality checks and switch statements.

The cryptographic operations are implemented using constant-time algorithms.

func P521

func P521() Curve

P521 returns a Curve which implements NIST P-521 (FIPS 186-3, section D.2.5), also known as secp521r1. The CurveParams.Name of this Curve is “P-521”.

Multiple invocations of this function will return the same value, so it can be used for equality checks and switch statements.

The cryptographic operations are implemented using constant-time algorithms.

type CurveParams

type CurveParams struct {
	P       *big.Int // the order of the underlying field
	N       *big.Int // the order of the base point
	B       *big.Int // the constant of the curve equation
	Gx, Gy  *big.Int // (x,y) of the base point
	BitSize int      // the size of the underlying field
	Name    string   // the canonical name of the curve
}

CurveParams contains the parameters of an elliptic curve and also provides a generic, non-constant time implementation of Curve.

Note: Custom curves (those not returned by P224(), P256(), P384(), and P521()) are not guaranteed to provide any security property.

(*CurveParams) Add

func (curve *CurveParams) Add(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int)

Add implements Curve.Add.

Note: the CurveParams methods are not guaranteed to provide any security property. For ECDH, use the crypto/ecdh package. For ECDSA, use the crypto/ecdsa package with a Curve value returned directly from P224(), P256(), P384(), or P521().

(*CurveParams) Double

func (curve *CurveParams) Double(x1, y1 *big.Int) (*big.Int, *big.Int)

Double implements Curve.Double.

Note: the CurveParams methods are not guaranteed to provide any security property. For ECDH, use the crypto/ecdh package. For ECDSA, use the crypto/ecdsa package with a Curve value returned directly from P224(), P256(), P384(), or P521().

(*CurveParams) IsOnCurve

func (curve *CurveParams) IsOnCurve(x, y *big.Int) bool

IsOnCurve implements Curve.IsOnCurve.

Note: the CurveParams methods are not guaranteed to provide any security property. For ECDH, use the crypto/ecdh package. For ECDSA, use the crypto/ecdsa package with a Curve value returned directly from P224(), P256(), P384(), or P521().

(*CurveParams) Params

func (curve *CurveParams) Params() *CurveParams

(*CurveParams) ScalarBaseMult

func (curve *CurveParams) ScalarBaseMult(k []byte) (*big.Int, *big.Int)

ScalarBaseMult implements Curve.ScalarBaseMult.

Note: the CurveParams methods are not guaranteed to provide any security property. For ECDH, use the crypto/ecdh package. For ECDSA, use the crypto/ecdsa package with a Curve value returned directly from P224(), P256(), P384(), or P521().

(*CurveParams) ScalarMult

func (curve *CurveParams) ScalarMult(Bx, By *big.Int, k []byte) (*big.Int, *big.Int)

ScalarMult implements Curve.ScalarMult.

Note: the CurveParams methods are not guaranteed to provide any security property. For ECDH, use the crypto/ecdh package. For ECDSA, use the crypto/ecdsa package with a Curve value returned directly from P224(), P256(), P384(), or P521().

4.10 - hmac

hmac

https://pkg.go.dev/crypto/hmac@go1.20.1

Package hmac implements the Keyed-Hash Message Authentication Code (HMAC) as defined in U.S. Federal Information Processing Standards Publication 198. An HMAC is a cryptographic hash that uses a key to sign a message. The receiver verifies the hash by recomputing it using the same key.

Receivers should be careful to use Equal to compare MACs in order to avoid timing side-channels:

// ValidMAC reports whether messageMAC is a valid HMAC tag for message.
func ValidMAC(message, messageMAC, key []byte) bool {
	mac := hmac.New(sha256.New, key)
	mac.Write(message)
	expectedMAC := mac.Sum(nil)
	return hmac.Equal(messageMAC, expectedMAC)
}

常量

This section is empty.

变量

This section is empty.

函数

func Equal added in go1.1

func Equal(mac1, mac2 []byte) bool

Equal compares two MACs for equality without leaking timing information.

func New

func New(h func() hash.Hash, key []byte) hash.Hash

New returns a new HMAC hash using the given hash.Hash type and key. New functions like sha256.New from crypto/sha256 can be used as h. h must return a new Hash every time it is called. Note that unlike other hash implementations in the standard library, the returned Hash does not implement encoding.BinaryMarshaler or encoding.BinaryUnmarshaler.

类型

This section is empty.

4.11 - md5

md5

https://pkg.go.dev/crypto/md5@go1.20.1

Package md5 implements the MD5 hash algorithm as defined in RFC 1321.

MD5 is cryptographically broken and should not be used for secure applications.

常量

View Source

const BlockSize = 64

The blocksize of MD5 in bytes.

View Source

const Size = 16

The size of an MD5 checksum in bytes.

变量

This section is empty.

函数

func New

func New() hash.Hash

New returns a new hash.Hash computing the MD5 checksum. The Hash also implements encoding.BinaryMarshaler and encoding.BinaryUnmarshaler to marshal and unmarshal the internal state of the hash.

Example 
Example (File) 

func Sum added in go1.2

func Sum(data []byte) [Size]byte

Sum returns the MD5 checksum of the data.

Example 

类型

This section is empty.

4.12 - rand

rand

https://pkg.go.dev/crypto/rand@go1.20.1

Package rand implements a cryptographically secure random number generator.

常量

This section is empty.

变量

View Source

var Reader io.Reader

Reader is a global, shared instance of a cryptographically secure random number generator.

On Linux, FreeBSD, Dragonfly and Solaris, Reader uses getrandom(2) if available, /dev/urandom otherwise. On OpenBSD and macOS, Reader uses getentropy(2). On other Unix-like systems, Reader reads from /dev/urandom. On Windows systems, Reader uses the RtlGenRandom API. On Wasm, Reader uses the Web Crypto API.

函数

func Int

func Int(rand io.Reader, max *big.Int) (n *big.Int, err error)

Int returns a uniform random value in [0, max). It panics if max <= 0.

func Prime

func Prime(rand io.Reader, bits int) (*big.Int, error)

Prime returns a number of the given bit length that is prime with high probability. Prime will return error for any error returned by rand.Read or if bits < 2.

func Read

func Read(b []byte) (n int, err error)

Read is a helper function that calls Reader.Read using io.ReadFull. On return, n == len(b) if and only if err == nil.

Example 

类型

This section is empty.

4.13 - rc4

rc4

https://pkg.go.dev/crypto/rc4@go1.20.1

Package rc4 implements RC4 encryption, as defined in Bruce Schneier’s Applied Cryptography.

RC4 is cryptographically broken and should not be used for secure applications.

常量

This section is empty.

变量

This section is empty.

函数

This section is empty.

类型

type Cipher

type Cipher struct {
	// contains filtered or unexported fields
}

A Cipher is an instance of RC4 using a particular key.

func NewCipher

func NewCipher(key []byte) (*Cipher, error)

NewCipher creates and returns a new Cipher. The key argument should be the RC4 key, at least 1 byte and at most 256 bytes.

func (*Cipher)ResetDEPRECATED

(*Cipher) XORKeyStream

func (c *Cipher) XORKeyStream(dst, src []byte)

XORKeyStream sets dst to the result of XORing src with the key stream. Dst and src must overlap entirely or not at all.

type KeySizeError

type KeySizeError int

(KeySizeError) Error

func (k KeySizeError) Error() string

4.14 - rsa

rsa

https://pkg.go.dev/crypto/rsa@go1.20.1

Package rsa implements RSA encryption as specified in PKCS #1 and RFC 8017.

RSA is a single, fundamental operation that is used in this package to implement either public-key encryption or public-key signatures.

The original specification for encryption and signatures with RSA is PKCS #1 and the terms “RSA encryption” and “RSA signatures” by default refer to PKCS #1 version 1.5. However, that specification has flaws and new designs should use version 2, usually called by just OAEP and PSS, where possible.

Two sets of interfaces are included in this package. When a more abstract interface isn’t necessary, there are functions for encrypting/decrypting with v1.5/OAEP and signing/verifying with v1.5/PSS. If one needs to abstract over the public key primitive, the PrivateKey type implements the Decrypter and Signer interfaces from the crypto package.

Operations in this package are implemented using constant-time algorithms, except for GenerateKey, PrivateKey.Precompute, and PrivateKey.Validate. Every other operation only leaks the bit size of the involved values, which all depend on the selected key size.

常量

View Source

const (
	// PSSSaltLengthAuto causes the salt in a PSS signature to be as large
	// as possible when signing, and to be auto-detected when verifying.
	PSSSaltLengthAuto = 0
	// PSSSaltLengthEqualsHash causes the salt length to equal the length
	// of the hash used in the signature.
	PSSSaltLengthEqualsHash = -1
)

变量

View Source

var ErrDecryption = errors.New("crypto/rsa: decryption error")

ErrDecryption represents a failure to decrypt a message. It is deliberately vague to avoid adaptive attacks.

View Source

var ErrMessageTooLong = errors.New("crypto/rsa: message too long for RSA key size")

ErrMessageTooLong is returned when attempting to encrypt or sign a message which is too large for the size of the key. When using SignPSS, this can also be returned if the size of the salt is too large.

View Source

var ErrVerification = errors.New("crypto/rsa: verification error")

ErrVerification represents a failure to verify a signature. It is deliberately vague to avoid adaptive attacks.

函数

func DecryptOAEP

func DecryptOAEP(hash hash.Hash, random io.Reader, priv *PrivateKey, ciphertext []byte, label []byte) ([]byte, error)

DecryptOAEP decrypts ciphertext using RSA-OAEP.

OAEP is parameterised by a hash function that is used as a random oracle. Encryption and decryption of a given message must use the same hash function and sha256.New() is a reasonable choice.

The random parameter is legacy and ignored, and it can be as nil.

The label parameter must match the value given when encrypting. See EncryptOAEP for details.

Example 

func DecryptPKCS1v15

func DecryptPKCS1v15(random io.Reader, priv *PrivateKey, ciphertext []byte) ([]byte, error)

DecryptPKCS1v15 decrypts a plaintext using RSA and the padding scheme from PKCS #1 v1.5. The random parameter is legacy and ignored, and it can be as nil.

Note that whether this function returns an error or not discloses secret information. If an attacker can cause this function to run repeatedly and learn whether each instance returned an error then they can decrypt and forge signatures as if they had the private key. See DecryptPKCS1v15SessionKey for a way of solving this problem.

func DecryptPKCS1v15SessionKey

func DecryptPKCS1v15SessionKey(random io.Reader, priv *PrivateKey, ciphertext []byte, key []byte) error

DecryptPKCS1v15SessionKey decrypts a session key using RSA and the padding scheme from PKCS #1 v1.5. The random parameter is legacy and ignored, and it can be as nil. It returns an error if the ciphertext is the wrong length or if the ciphertext is greater than the public modulus. Otherwise, no error is returned. If the padding is valid, the resulting plaintext message is copied into key. Otherwise, key is unchanged. These alternatives occur in constant time. It is intended that the user of this function generate a random session key beforehand and continue the protocol with the resulting value. This will remove any possibility that an attacker can learn any information about the plaintext. See “Chosen Ciphertext Attacks Against Protocols Based on the RSA Encryption Standard PKCS #1”, Daniel Bleichenbacher, Advances in Cryptology (Crypto ‘98).

Note that if the session key is too small then it may be possible for an attacker to brute-force it. If they can do that then they can learn whether a random value was used (because it’ll be different for the same ciphertext) and thus whether the padding was correct. This defeats the point of this function. Using at least a 16-byte key will protect against this attack.

Example 

func EncryptOAEP

func EncryptOAEP(hash hash.Hash, random io.Reader, pub *PublicKey, msg []byte, label []byte) ([]byte, error)

EncryptOAEP encrypts the given message with RSA-OAEP.

OAEP is parameterised by a hash function that is used as a random oracle. Encryption and decryption of a given message must use the same hash function and sha256.New() is a reasonable choice.

The random parameter is used as a source of entropy to ensure that encrypting the same message twice doesn’t result in the same ciphertext.

The label parameter may contain arbitrary data that will not be encrypted, but which gives important context to the message. For example, if a given public key is used to encrypt two types of messages then distinct label values could be used to ensure that a ciphertext for one purpose cannot be used for another by an attacker. If not required it can be empty.

The message must be no longer than the length of the public modulus minus twice the hash length, minus a further 2.

Example 

func EncryptPKCS1v15

func EncryptPKCS1v15(random io.Reader, pub *PublicKey, msg []byte) ([]byte, error)

EncryptPKCS1v15 encrypts the given message with RSA and the padding scheme from PKCS #1 v1.5. The message must be no longer than the length of the public modulus minus 11 bytes.

The random parameter is used as a source of entropy to ensure that encrypting the same message twice doesn’t result in the same ciphertext.

WARNING: use of this function to encrypt plaintexts other than session keys is dangerous. Use RSA OAEP in new protocols.

func SignPKCS1v15

func SignPKCS1v15(random io.Reader, priv *PrivateKey, hash crypto.Hash, hashed []byte) ([]byte, error)

SignPKCS1v15 calculates the signature of hashed using RSASSA-PKCS1-V1_5-SIGN from RSA PKCS #1 v1.5. Note that hashed must be the result of hashing the input message using the given hash function. If hash is zero, hashed is signed directly. This isn’t advisable except for interoperability.

The random parameter is legacy and ignored, and it can be as nil.

This function is deterministic. Thus, if the set of possible messages is small, an attacker may be able to build a map from messages to signatures and identify the signed messages. As ever, signatures provide authenticity, not confidentiality.

Example 

func SignPSS added in go1.2

func SignPSS(rand io.Reader, priv *PrivateKey, hash crypto.Hash, digest []byte, opts *PSSOptions) ([]byte, error)

SignPSS calculates the signature of digest using PSS.

digest must be the result of hashing the input message using the given hash function. The opts argument may be nil, in which case sensible defaults are used. If opts.Hash is set, it overrides hash.

func VerifyPKCS1v15

func VerifyPKCS1v15(pub *PublicKey, hash crypto.Hash, hashed []byte, sig []byte) error

VerifyPKCS1v15 verifies an RSA PKCS #1 v1.5 signature. hashed is the result of hashing the input message using the given hash function and sig is the signature. A valid signature is indicated by returning a nil error. If hash is zero then hashed is used directly. This isn’t advisable except for interoperability.

Example 

func VerifyPSS added in go1.2

func VerifyPSS(pub *PublicKey, hash crypto.Hash, digest []byte, sig []byte, opts *PSSOptions) error

VerifyPSS verifies a PSS signature.

A valid signature is indicated by returning a nil error. digest must be the result of hashing the input message using the given hash function. The opts argument may be nil, in which case sensible defaults are used. opts.Hash is ignored.

类型

type CRTValue

type CRTValue struct {
	Exp   *big.Int // D mod (prime-1).
	Coeff *big.Int // R·Coeff ≡ 1 mod Prime.
	R     *big.Int // product of primes prior to this (inc p and q).
}

CRTValue contains the precomputed Chinese remainder theorem values.

type OAEPOptions added in go1.5

type OAEPOptions struct {
	// Hash is the hash function that will be used when generating the mask.
	Hash crypto.Hash

	// MGFHash is the hash function used for MGF1.
	// If zero, Hash is used instead.
	MGFHash crypto.Hash

	// Label is an arbitrary byte string that must be equal to the value
	// used when encrypting.
	Label []byte
}

OAEPOptions is an interface for passing options to OAEP decryption using the crypto.Decrypter interface.

type PKCS1v15DecryptOptions added in go1.5

type PKCS1v15DecryptOptions struct {
	// SessionKeyLen is the length of the session key that is being
	// decrypted. If not zero, then a padding error during decryption will
	// cause a random plaintext of this length to be returned rather than
	// an error. These alternatives happen in constant time.
	SessionKeyLen int
}

PKCS1v15DecryptOptions is for passing options to PKCS #1 v1.5 decryption using the crypto.Decrypter interface.

type PSSOptions added in go1.2

type PSSOptions struct {
	// SaltLength controls the length of the salt used in the PSS signature. It
	// can either be a positive number of bytes, or one of the special
	// PSSSaltLength constants.
	SaltLength int

	// Hash is the hash function used to generate the message digest. If not
	// zero, it overrides the hash function passed to SignPSS. It's required
	// when using PrivateKey.Sign.
	Hash crypto.Hash
}

PSSOptions contains options for creating and verifying PSS signatures.

(*PSSOptions) HashFunc added in go1.4

func (opts *PSSOptions) HashFunc() crypto.Hash

HashFunc returns opts.Hash so that PSSOptions implements crypto.SignerOpts.

type PrecomputedValues

type PrecomputedValues struct {
	Dp, Dq *big.Int // D mod (P-1) (or mod Q-1)
	Qinv   *big.Int // Q^-1 mod P

	// CRTValues is used for the 3rd and subsequent primes. Due to a
	// historical accident, the CRT for the first two primes is handled
	// differently in PKCS #1 and interoperability is sufficiently
	// important that we mirror this.
	//
	// Note: these values are still filled in by Precompute for
	// backwards compatibility but are not used. Multi-prime RSA is very rare,
	// and is implemented by this package without CRT optimizations to limit
	// complexity.
	CRTValues []CRTValue
	// contains filtered or unexported fields
}

type PrivateKey

type PrivateKey struct {
	PublicKey            // public part.
	D         *big.Int   // private exponent
	Primes    []*big.Int // prime factors of N, has >= 2 elements.

	// Precomputed contains precomputed values that speed up RSA operations,
	// if available. It must be generated by calling PrivateKey.Precompute and
	// must not be modified.
	Precomputed PrecomputedValues
}

A PrivateKey represents an RSA key

func GenerateKey

func GenerateKey(random io.Reader, bits int) (*PrivateKey, error)

GenerateKey generates an RSA keypair of the given bit size using the random source random (for example, crypto/rand.Reader).

func GenerateMultiPrimeKey

func GenerateMultiPrimeKey(random io.Reader, nprimes int, bits int) (*PrivateKey, error)

GenerateMultiPrimeKey generates a multi-prime RSA keypair of the given bit size and the given random source.

Table 1 in “On the Security of Multi-prime RSA” suggests maximum numbers of primes for a given bit size.

Although the public keys are compatible (actually, indistinguishable) from the 2-prime case, the private keys are not. Thus it may not be possible to export multi-prime private keys in certain formats or to subsequently import them into other code.

This package does not implement CRT optimizations for multi-prime RSA, so the keys with more than two primes will have worse performance.

Note: The use of this function with a number of primes different from two is not recommended for the above security, compatibility, and performance reasons. Use GenerateKey instead.

(*PrivateKey) Decrypt added in go1.5

func (priv *PrivateKey) Decrypt(rand io.Reader, ciphertext []byte, opts crypto.DecrypterOpts) (plaintext []byte, err error)

Decrypt decrypts ciphertext with priv. If opts is nil or of type *PKCS1v15DecryptOptions then PKCS #1 v1.5 decryption is performed. Otherwise opts must have type *OAEPOptions and OAEP decryption is done.

(*PrivateKey) Equal added in go1.15

func (priv *PrivateKey) Equal(x crypto.PrivateKey) bool

Equal reports whether priv and x have equivalent values. It ignores Precomputed values.

(*PrivateKey) Precompute

func (priv *PrivateKey) Precompute()

Precompute performs some calculations that speed up private key operations in the future.

(*PrivateKey) Public added in go1.4

func (priv *PrivateKey) Public() crypto.PublicKey

Public returns the public key corresponding to priv.

(*PrivateKey) Sign added in go1.4

func (priv *PrivateKey) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error)

Sign signs digest with priv, reading randomness from rand. If opts is a *PSSOptions then the PSS algorithm will be used, otherwise PKCS #1 v1.5 will be used. digest must be the result of hashing the input message using opts.HashFunc().

This method implements crypto.Signer, which is an interface to support keys where the private part is kept in, for example, a hardware module. Common uses should use the Sign* functions in this package directly.

(*PrivateKey) Validate

func (priv *PrivateKey) Validate() error

Validate performs basic sanity checks on the key. It returns nil if the key is valid, or else an error describing a problem.

type PublicKey

type PublicKey struct {
	N *big.Int // modulus
	E int      // public exponent
}

A PublicKey represents the public part of an RSA key.

(*PublicKey) Equal added in go1.15

func (pub *PublicKey) Equal(x crypto.PublicKey) bool

Equal reports whether pub and x have the same value.

(*PublicKey) Size added in go1.11

func (pub *PublicKey) Size() int

Size returns the modulus size in bytes. Raw signatures and ciphertexts for or by this public key will have the same size.

4.15 - sha1

sha1

https://pkg.go.dev/crypto/sha1@go1.20.1

Package sha1 implements the SHA-1 hash algorithm as defined in RFC 3174.

SHA-1 is cryptographically broken and should not be used for secure applications.

常量

View Source

const BlockSize = 64

The blocksize of SHA-1 in bytes.

View Source

const Size = 20

The size of a SHA-1 checksum in bytes.

变量

This section is empty.

函数

func New

func New() hash.Hash

New returns a new hash.Hash computing the SHA1 checksum. The Hash also implements encoding.BinaryMarshaler and encoding.BinaryUnmarshaler to marshal and unmarshal the internal state of the hash.

Example 
Example (File) 

func Sum added in go1.2

func Sum(data []byte) [Size]byte

Sum returns the SHA-1 checksum of the data.

Example 

类型

This section is empty.

4.16 - sha256

sha256

https://pkg.go.dev/crypto/sha256@go1.20.1

Package sha256 implements the SHA224 and SHA256 hash algorithms as defined in FIPS 180-4.

常量

View Source

const BlockSize = 64

The blocksize of SHA256 and SHA224 in bytes.

View Source

const Size = 32

The size of a SHA256 checksum in bytes.

View Source

const Size224 = 28

The size of a SHA224 checksum in bytes.

变量

This section is empty.

函数

func New

func New() hash.Hash

New returns a new hash.Hash computing the SHA256 checksum. The Hash also implements encoding.BinaryMarshaler and encoding.BinaryUnmarshaler to marshal and unmarshal the internal state of the hash.

Example 
Example (File) 

func New224

func New224() hash.Hash

New224 returns a new hash.Hash computing the SHA224 checksum.

func Sum224 added in go1.2

func Sum224(data []byte) [Size224]byte

Sum224 returns the SHA224 checksum of the data.

func Sum256 added in go1.2

func Sum256(data []byte) [Size]byte

Sum256 returns the SHA256 checksum of the data.

Example 

类型

This section is empty.

4.17 - sha512

sha512

https://pkg.go.dev/crypto/sha512@go1.20.1

Package sha512 implements the SHA-384, SHA-512, SHA-512/224, and SHA-512/256 hash algorithms as defined in FIPS 180-4.

All the hash.Hash implementations returned by this package also implement encoding.BinaryMarshaler and encoding.BinaryUnmarshaler to marshal and unmarshal the internal state of the hash.

常量

View Source

const (
	// Size is the size, in bytes, of a SHA-512 checksum.
	Size = 64

	// Size224 is the size, in bytes, of a SHA-512/224 checksum.
	Size224 = 28

	// Size256 is the size, in bytes, of a SHA-512/256 checksum.
	Size256 = 32

	// Size384 is the size, in bytes, of a SHA-384 checksum.
	Size384 = 48

	// BlockSize is the block size, in bytes, of the SHA-512/224,
	// SHA-512/256, SHA-384 and SHA-512 hash functions.
	BlockSize = 128
)

变量

This section is empty.

函数

func New

func New() hash.Hash

New returns a new hash.Hash computing the SHA-512 checksum.

func New384

func New384() hash.Hash

New384 returns a new hash.Hash computing the SHA-384 checksum.

func New512_224 added in go1.5

func New512_224() hash.Hash

New512_224 returns a new hash.Hash computing the SHA-512/224 checksum.

func New512_256 added in go1.5

func New512_256() hash.Hash

New512_256 returns a new hash.Hash computing the SHA-512/256 checksum.

func Sum384 added in go1.2

func Sum384(data []byte) [Size384]byte

Sum384 returns the SHA384 checksum of the data.

func Sum512 added in go1.2

func Sum512(data []byte) [Size]byte

Sum512 returns the SHA512 checksum of the data.

func Sum512_224 added in go1.5

func Sum512_224(data []byte) [Size224]byte

Sum512_224 returns the Sum512/224 checksum of the data.

func Sum512_256 added in go1.5

func Sum512_256(data []byte) [Size256]byte

Sum512_256 returns the Sum512/256 checksum of the data.

类型

This section is empty.

4.18 - subtle

subtle

https://pkg.go.dev/crypto/subtle@go1.20.1

Package subtle implements functions that are often useful in cryptographic code but require careful thought to use correctly.

常量

This section is empty.

变量

This section is empty.

函数

func ConstantTimeByteEq

func ConstantTimeByteEq(x, y uint8) int

ConstantTimeByteEq returns 1 if x == y and 0 otherwise.

func ConstantTimeCompare

func ConstantTimeCompare(x, y []byte) int

ConstantTimeCompare returns 1 if the two slices, x and y, have equal contents and 0 otherwise. The time taken is a function of the length of the slices and is independent of the contents. If the lengths of x and y do not match it returns 0 immediately.

func ConstantTimeCopy

func ConstantTimeCopy(v int, x, y []byte)

ConstantTimeCopy copies the contents of y into x (a slice of equal length) if v == 1. If v == 0, x is left unchanged. Its behavior is undefined if v takes any other value.

func ConstantTimeEq

func ConstantTimeEq(x, y int32) int

ConstantTimeEq returns 1 if x == y and 0 otherwise.

func ConstantTimeLessOrEq added in go1.2

func ConstantTimeLessOrEq(x, y int) int

ConstantTimeLessOrEq returns 1 if x <= y and 0 otherwise. Its behavior is undefined if x or y are negative or > 2**31 - 1.

func ConstantTimeSelect

func ConstantTimeSelect(v, x, y int) int

ConstantTimeSelect returns x if v == 1 and y if v == 0. Its behavior is undefined if v takes any other value.

func XORBytes added in go1.20

func XORBytes(dst, x, y []byte) int

XORBytes sets dst[i] = x[i] ^ y[i] for all i < n = min(len(x), len(y)), returning n, the number of bytes written to dst. If dst does not have length at least n, XORBytes panics without writing anything to dst.

类型

This section is empty.

4.19 - tls

tls

https://pkg.go.dev/crypto/tls@go1.20.1

Package tls partially implements TLS 1.2, as specified in RFC 5246, and TLS 1.3, as specified in RFC 8446.

常量

View Source

const (
	// TLS 1.0 - 1.2 cipher suites.
	TLS_RSA_WITH_RC4_128_SHA                      uint16 = 0x0005
	TLS_RSA_WITH_3DES_EDE_CBC_SHA                 uint16 = 0x000a
	TLS_RSA_WITH_AES_128_CBC_SHA                  uint16 = 0x002f
	TLS_RSA_WITH_AES_256_CBC_SHA                  uint16 = 0x0035
	TLS_RSA_WITH_AES_128_CBC_SHA256               uint16 = 0x003c
	TLS_RSA_WITH_AES_128_GCM_SHA256               uint16 = 0x009c
	TLS_RSA_WITH_AES_256_GCM_SHA384               uint16 = 0x009d
	TLS_ECDHE_ECDSA_WITH_RC4_128_SHA              uint16 = 0xc007
	TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA          uint16 = 0xc009
	TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA          uint16 = 0xc00a
	TLS_ECDHE_RSA_WITH_RC4_128_SHA                uint16 = 0xc011
	TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA           uint16 = 0xc012
	TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA            uint16 = 0xc013
	TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA            uint16 = 0xc014
	TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256       uint16 = 0xc023
	TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256         uint16 = 0xc027
	TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256         uint16 = 0xc02f
	TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256       uint16 = 0xc02b
	TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384         uint16 = 0xc030
	TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384       uint16 = 0xc02c
	TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256   uint16 = 0xcca8
	TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xcca9

	// TLS 1.3 cipher suites.
	TLS_AES_128_GCM_SHA256       uint16 = 0x1301
	TLS_AES_256_GCM_SHA384       uint16 = 0x1302
	TLS_CHACHA20_POLY1305_SHA256 uint16 = 0x1303

	// TLS_FALLBACK_SCSV isn't a standard cipher suite but an indicator
	// that the client is doing version fallback. See RFC 7507.
	TLS_FALLBACK_SCSV uint16 = 0x5600

	// Legacy names for the corresponding cipher suites with the correct _SHA256
	// suffix, retained for backward compatibility.
	TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305   = TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256
	TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305 = TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
)

A list of cipher suite IDs that are, or have been, implemented by this package.

See https://www.iana.org/assignments/tls-parameters/tls-parameters.xml

View Source

const (
	VersionTLS10 = 0x0301
	VersionTLS11 = 0x0302
	VersionTLS12 = 0x0303
	VersionTLS13 = 0x0304

	// Deprecated: SSLv3 is cryptographically broken, and is no longer
	// supported by this package. See golang.org/issue/32716.
	VersionSSL30 = 0x0300
)

变量

This section is empty.

函数

func CipherSuiteName added in go1.14

func CipherSuiteName(id uint16) string

CipherSuiteName returns the standard name for the passed cipher suite ID (e.g. “TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256”), or a fallback representation of the ID value if the cipher suite is not implemented by this package.

func Listen

func Listen(network, laddr string, config *Config) (net.Listener, error)

Listen creates a TLS listener accepting connections on the given network address using net.Listen. The configuration config must be non-nil and must include at least one certificate or else set GetCertificate.

func NewListener

func NewListener(inner net.Listener, config *Config) net.Listener

NewListener creates a Listener which accepts connections from an inner Listener and wraps each connection with Server. The configuration config must be non-nil and must include at least one certificate or else set GetCertificate.

类型

type Certificate

type Certificate struct {
	Certificate [][]byte
	// PrivateKey contains the private key corresponding to the public key in
	// Leaf. This must implement crypto.Signer with an RSA, ECDSA or Ed25519 PublicKey.
	// For a server up to TLS 1.2, it can also implement crypto.Decrypter with
	// an RSA PublicKey.
	PrivateKey crypto.PrivateKey
	// SupportedSignatureAlgorithms is an optional list restricting what
	// signature algorithms the PrivateKey can be used for.
	SupportedSignatureAlgorithms []SignatureScheme
	// OCSPStaple contains an optional OCSP response which will be served
	// to clients that request it.
	OCSPStaple []byte
	// SignedCertificateTimestamps contains an optional list of Signed
	// Certificate Timestamps which will be served to clients that request it.
	SignedCertificateTimestamps [][]byte
	// Leaf is the parsed form of the leaf certificate, which may be initialized
	// using x509.ParseCertificate to reduce per-handshake processing. If nil,
	// the leaf certificate will be parsed as needed.
	Leaf *x509.Certificate
}

A Certificate is a chain of one or more certificates, leaf first.

func LoadX509KeyPair

func LoadX509KeyPair(certFile, keyFile string) (Certificate, error)

LoadX509KeyPair reads and parses a public/private key pair from a pair of files. The files must contain PEM encoded data. The certificate file may contain intermediate certificates following the leaf certificate to form a certificate chain. On successful return, Certificate.Leaf will be nil because the parsed form of the certificate is not retained.

Example 

func X509KeyPair

func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (Certificate, error)

X509KeyPair parses a public/private key pair from a pair of PEM encoded data. On successful return, Certificate.Leaf will be nil because the parsed form of the certificate is not retained.

Example 
Example (HttpServer) 

type CertificateRequestInfo added in go1.8

type CertificateRequestInfo struct {
	// AcceptableCAs contains zero or more, DER-encoded, X.501
	// Distinguished Names. These are the names of root or intermediate CAs
	// that the server wishes the returned certificate to be signed by. An
	// empty slice indicates that the server has no preference.
	AcceptableCAs [][]byte

	// SignatureSchemes lists the signature schemes that the server is
	// willing to verify.
	SignatureSchemes []SignatureScheme

	// Version is the TLS version that was negotiated for this connection.
	Version uint16
	// contains filtered or unexported fields
}

CertificateRequestInfo contains information from a server’s CertificateRequest message, which is used to demand a certificate and proof of control from a client.

(*CertificateRequestInfo) Context added in go1.17

func (c *CertificateRequestInfo) Context() context.Context

Context returns the context of the handshake that is in progress. This context is a child of the context passed to HandshakeContext, if any, and is canceled when the handshake concludes.

(*CertificateRequestInfo) SupportsCertificate added in go1.14

func (cri *CertificateRequestInfo) SupportsCertificate(c *Certificate) error

SupportsCertificate returns nil if the provided certificate is supported by the server that sent the CertificateRequest. Otherwise, it returns an error describing the reason for the incompatibility.

type CertificateVerificationError added in go1.20

type CertificateVerificationError struct {
	// UnverifiedCertificates and its contents should not be modified.
	UnverifiedCertificates []*x509.Certificate
	Err                    error
}

CertificateVerificationError is returned when certificate verification fails during the handshake.

(*CertificateVerificationError) Error added in go1.20

func (e *CertificateVerificationError) Error() string

(*CertificateVerificationError) Unwrap added in go1.20

func (e *CertificateVerificationError) Unwrap() error

type CipherSuite added in go1.14

type CipherSuite struct {
	ID   uint16
	Name string

	// Supported versions is the list of TLS protocol versions that can
	// negotiate this cipher suite.
	SupportedVersions []uint16

	// Insecure is true if the cipher suite has known security issues
	// due to its primitives, design, or implementation.
	Insecure bool
}

CipherSuite is a TLS cipher suite. Note that most functions in this package accept and expose cipher suite IDs instead of this type.

func CipherSuites added in go1.14

func CipherSuites() []*CipherSuite

CipherSuites returns a list of cipher suites currently implemented by this package, excluding those with security issues, which are returned by InsecureCipherSuites.

The list is sorted by ID. Note that the default cipher suites selected by this package might depend on logic that can’t be captured by a static list, and might not match those returned by this function.

func InsecureCipherSuites added in go1.14

func InsecureCipherSuites() []*CipherSuite

InsecureCipherSuites returns a list of cipher suites currently implemented by this package and which have security issues.

Most applications should not use the cipher suites in this list, and should only use those returned by CipherSuites.

type ClientAuthType

type ClientAuthType int

ClientAuthType declares the policy the server will follow for TLS Client Authentication.

const (
	// NoClientCert indicates that no client certificate should be requested
	// during the handshake, and if any certificates are sent they will not
	// be verified.
	NoClientCert ClientAuthType = iota
	// RequestClientCert indicates that a client certificate should be requested
	// during the handshake, but does not require that the client send any
	// certificates.
	RequestClientCert
	// RequireAnyClientCert indicates that a client certificate should be requested
	// during the handshake, and that at least one certificate is required to be
	// sent by the client, but that certificate is not required to be valid.
	RequireAnyClientCert
	// VerifyClientCertIfGiven indicates that a client certificate should be requested
	// during the handshake, but does not require that the client sends a
	// certificate. If the client does send a certificate it is required to be
	// valid.
	VerifyClientCertIfGiven
	// RequireAndVerifyClientCert indicates that a client certificate should be requested
	// during the handshake, and that at least one valid certificate is required
	// to be sent by the client.
	RequireAndVerifyClientCert
)

(ClientAuthType) String added in go1.15

func (i ClientAuthType) String() string

type ClientHelloInfo added in go1.4

type ClientHelloInfo struct {
	// CipherSuites lists the CipherSuites supported by the client (e.g.
	// TLS_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256).
	CipherSuites []uint16

	// ServerName indicates the name of the server requested by the client
	// in order to support virtual hosting. ServerName is only set if the
	// client is using SNI (see RFC 4366, Section 3.1).
	ServerName string

	// SupportedCurves lists the elliptic curves supported by the client.
	// SupportedCurves is set only if the Supported Elliptic Curves
	// Extension is being used (see RFC 4492, Section 5.1.1).
	SupportedCurves []CurveID

	// SupportedPoints lists the point formats supported by the client.
	// SupportedPoints is set only if the Supported Point Formats Extension
	// is being used (see RFC 4492, Section 5.1.2).
	SupportedPoints []uint8

	// SignatureSchemes lists the signature and hash schemes that the client
	// is willing to verify. SignatureSchemes is set only if the Signature
	// Algorithms Extension is being used (see RFC 5246, Section 7.4.1.4.1).
	SignatureSchemes []SignatureScheme

	// SupportedProtos lists the application protocols supported by the client.
	// SupportedProtos is set only if the Application-Layer Protocol
	// Negotiation Extension is being used (see RFC 7301, Section 3.1).
	//
	// Servers can select a protocol by setting Config.NextProtos in a
	// GetConfigForClient return value.
	SupportedProtos []string

	// SupportedVersions lists the TLS versions supported by the client.
	// For TLS versions less than 1.3, this is extrapolated from the max
	// version advertised by the client, so values other than the greatest
	// might be rejected if used.
	SupportedVersions []uint16

	// Conn is the underlying net.Conn for the connection. Do not read
	// from, or write to, this connection; that will cause the TLS
	// connection to fail.
	Conn net.Conn
	// contains filtered or unexported fields
}

ClientHelloInfo contains information from a ClientHello message in order to guide application logic in the GetCertificate and GetConfigForClient callbacks.

(*ClientHelloInfo) Context added in go1.17

func (c *ClientHelloInfo) Context() context.Context

Context returns the context of the handshake that is in progress. This context is a child of the context passed to HandshakeContext, if any, and is canceled when the handshake concludes.

(*ClientHelloInfo) SupportsCertificate added in go1.14

func (chi *ClientHelloInfo) SupportsCertificate(c *Certificate) error

SupportsCertificate returns nil if the provided certificate is supported by the client that sent the ClientHello. Otherwise, it returns an error describing the reason for the incompatibility.

If this ClientHelloInfo was passed to a GetConfigForClient or GetCertificate callback, this method will take into account the associated Config. Note that if GetConfigForClient returns a different Config, the change can’t be accounted for by this method.

This function will call x509.ParseCertificate unless c.Leaf is set, which can incur a significant performance cost.

type ClientSessionCache added in go1.3

type ClientSessionCache interface {
	// Get searches for a ClientSessionState associated with the given key.
	// On return, ok is true if one was found.
	Get(sessionKey string) (session *ClientSessionState, ok bool)

	// Put adds the ClientSessionState to the cache with the given key. It might
	// get called multiple times in a connection if a TLS 1.3 server provides
	// more than one session ticket. If called with a nil *ClientSessionState,
	// it should remove the cache entry.
	Put(sessionKey string, cs *ClientSessionState)
}

ClientSessionCache is a cache of ClientSessionState objects that can be used by a client to resume a TLS session with a given server. ClientSessionCache implementations should expect to be called concurrently from different goroutines. Up to TLS 1.2, only ticket-based resumption is supported, not SessionID-based resumption. In TLS 1.3 they were merged into PSK modes, which are supported via this interface.

func NewLRUClientSessionCache added in go1.3

func NewLRUClientSessionCache(capacity int) ClientSessionCache

NewLRUClientSessionCache returns a ClientSessionCache with the given capacity that uses an LRU strategy. If capacity is < 1, a default capacity is used instead.

type ClientSessionState added in go1.3

type ClientSessionState struct {
	// contains filtered or unexported fields
}

ClientSessionState contains the state needed by clients to resume TLS sessions.

type Config

type Config struct {
	// Rand provides the source of entropy for nonces and RSA blinding.
	// If Rand is nil, TLS uses the cryptographic random reader in package
	// crypto/rand.
	// The Reader must be safe for use by multiple goroutines.
	Rand io.Reader

	// Time returns the current time as the number of seconds since the epoch.
	// If Time is nil, TLS uses time.Now.
	Time func() time.Time

	// Certificates contains one or more certificate chains to present to the
	// other side of the connection. The first certificate compatible with the
	// peer's requirements is selected automatically.
	//
	// Server configurations must set one of Certificates, GetCertificate or
	// GetConfigForClient. Clients doing client-authentication may set either
	// Certificates or GetClientCertificate.
	//
	// Note: if there are multiple Certificates, and they don't have the
	// optional field Leaf set, certificate selection will incur a significant
	// per-handshake performance cost.
	Certificates []Certificate

	// NameToCertificate maps from a certificate name to an element of
	// Certificates. Note that a certificate name can be of the form
	// '*.example.com' and so doesn't have to be a domain name as such.
	//
	// Deprecated: NameToCertificate only allows associating a single
	// certificate with a given name. Leave this field nil to let the library
	// select the first compatible chain from Certificates.
	NameToCertificate map[string]*Certificate

	// GetCertificate returns a Certificate based on the given
	// ClientHelloInfo. It will only be called if the client supplies SNI
	// information or if Certificates is empty.
	//
	// If GetCertificate is nil or returns nil, then the certificate is
	// retrieved from NameToCertificate. If NameToCertificate is nil, the
	// best element of Certificates will be used.
	//
	// Once a Certificate is returned it should not be modified.
	GetCertificate func(*ClientHelloInfo) (*Certificate, error)

	// GetClientCertificate, if not nil, is called when a server requests a
	// certificate from a client. If set, the contents of Certificates will
	// be ignored.
	//
	// If GetClientCertificate returns an error, the handshake will be
	// aborted and that error will be returned. Otherwise
	// GetClientCertificate must return a non-nil Certificate. If
	// Certificate.Certificate is empty then no certificate will be sent to
	// the server. If this is unacceptable to the server then it may abort
	// the handshake.
	//
	// GetClientCertificate may be called multiple times for the same
	// connection if renegotiation occurs or if TLS 1.3 is in use.
	//
	// Once a Certificate is returned it should not be modified.
	GetClientCertificate func(*CertificateRequestInfo) (*Certificate, error)

	// GetConfigForClient, if not nil, is called after a ClientHello is
	// received from a client. It may return a non-nil Config in order to
	// change the Config that will be used to handle this connection. If
	// the returned Config is nil, the original Config will be used. The
	// Config returned by this callback may not be subsequently modified.
	//
	// If GetConfigForClient is nil, the Config passed to Server() will be
	// used for all connections.
	//
	// If SessionTicketKey was explicitly set on the returned Config, or if
	// SetSessionTicketKeys was called on the returned Config, those keys will
	// be used. Otherwise, the original Config keys will be used (and possibly
	// rotated if they are automatically managed).
	GetConfigForClient func(*ClientHelloInfo) (*Config, error)

	// VerifyPeerCertificate, if not nil, is called after normal
	// certificate verification by either a TLS client or server. It
	// receives the raw ASN.1 certificates provided by the peer and also
	// any verified chains that normal processing found. If it returns a
	// non-nil error, the handshake is aborted and that error results.
	//
	// If normal verification fails then the handshake will abort before
	// considering this callback. If normal verification is disabled by
	// setting InsecureSkipVerify, or (for a server) when ClientAuth is
	// RequestClientCert or RequireAnyClientCert, then this callback will
	// be considered but the verifiedChains argument will always be nil.
	//
	// verifiedChains and its contents should not be modified.
	VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error

	// VerifyConnection, if not nil, is called after normal certificate
	// verification and after VerifyPeerCertificate by either a TLS client
	// or server. If it returns a non-nil error, the handshake is aborted
	// and that error results.
	//
	// If normal verification fails then the handshake will abort before
	// considering this callback. This callback will run for all connections
	// regardless of InsecureSkipVerify or ClientAuth settings.
	VerifyConnection func(ConnectionState) error

	// RootCAs defines the set of root certificate authorities
	// that clients use when verifying server certificates.
	// If RootCAs is nil, TLS uses the host's root CA set.
	RootCAs *x509.CertPool

	// NextProtos is a list of supported application level protocols, in
	// order of preference. If both peers support ALPN, the selected
	// protocol will be one from this list, and the connection will fail
	// if there is no mutually supported protocol. If NextProtos is empty
	// or the peer doesn't support ALPN, the connection will succeed and
	// ConnectionState.NegotiatedProtocol will be empty.
	NextProtos []string

	// ServerName is used to verify the hostname on the returned
	// certificates unless InsecureSkipVerify is given. It is also included
	// in the client's handshake to support virtual hosting unless it is
	// an IP address.
	ServerName string

	// ClientAuth determines the server's policy for
	// TLS Client Authentication. The default is NoClientCert.
	ClientAuth ClientAuthType

	// ClientCAs defines the set of root certificate authorities
	// that servers use if required to verify a client certificate
	// by the policy in ClientAuth.
	ClientCAs *x509.CertPool

	// InsecureSkipVerify controls whether a client verifies the server's
	// certificate chain and host name. If InsecureSkipVerify is true, crypto/tls
	// accepts any certificate presented by the server and any host name in that
	// certificate. In this mode, TLS is susceptible to machine-in-the-middle
	// attacks unless custom verification is used. This should be used only for
	// testing or in combination with VerifyConnection or VerifyPeerCertificate.
	InsecureSkipVerify bool

	// CipherSuites is a list of enabled TLS 1.0–1.2 cipher suites. The order of
	// the list is ignored. Note that TLS 1.3 ciphersuites are not configurable.
	//
	// If CipherSuites is nil, a safe default list is used. The default cipher
	// suites might change over time.
	CipherSuites []uint16

	// PreferServerCipherSuites is a legacy field and has no effect.
	//
	// It used to control whether the server would follow the client's or the
	// server's preference. Servers now select the best mutually supported
	// cipher suite based on logic that takes into account inferred client
	// hardware, server hardware, and security.
	//
	// Deprecated: PreferServerCipherSuites is ignored.
	PreferServerCipherSuites bool

	// SessionTicketsDisabled may be set to true to disable session ticket and
	// PSK (resumption) support. Note that on clients, session ticket support is
	// also disabled if ClientSessionCache is nil.
	SessionTicketsDisabled bool

	// SessionTicketKey is used by TLS servers to provide session resumption.
	// See RFC 5077 and the PSK mode of RFC 8446. If zero, it will be filled
	// with random data before the first server handshake.
	//
	// Deprecated: if this field is left at zero, session ticket keys will be
	// automatically rotated every day and dropped after seven days. For
	// customizing the rotation schedule or synchronizing servers that are
	// terminating connections for the same host, use SetSessionTicketKeys.
	SessionTicketKey [32]byte

	// ClientSessionCache is a cache of ClientSessionState entries for TLS
	// session resumption. It is only used by clients.
	ClientSessionCache ClientSessionCache

	// MinVersion contains the minimum TLS version that is acceptable.
	//
	// By default, TLS 1.2 is currently used as the minimum when acting as a
	// client, and TLS 1.0 when acting as a server. TLS 1.0 is the minimum
	// supported by this package, both as a client and as a server.
	//
	// The client-side default can temporarily be reverted to TLS 1.0 by
	// including the value "x509sha1=1" in the GODEBUG environment variable.
	// Note that this option will be removed in Go 1.19 (but it will still be
	// possible to set this field to VersionTLS10 explicitly).
	MinVersion uint16

	// MaxVersion contains the maximum TLS version that is acceptable.
	//
	// By default, the maximum version supported by this package is used,
	// which is currently TLS 1.3.
	MaxVersion uint16

	// CurvePreferences contains the elliptic curves that will be used in
	// an ECDHE handshake, in preference order. If empty, the default will
	// be used. The client will use the first preference as the type for
	// its key share in TLS 1.3. This may change in the future.
	CurvePreferences []CurveID

	// DynamicRecordSizingDisabled disables adaptive sizing of TLS records.
	// When true, the largest possible TLS record size is always used. When
	// false, the size of TLS records may be adjusted in an attempt to
	// improve latency.
	DynamicRecordSizingDisabled bool

	// Renegotiation controls what types of renegotiation are supported.
	// The default, none, is correct for the vast majority of applications.
	Renegotiation RenegotiationSupport

	// KeyLogWriter optionally specifies a destination for TLS master secrets
	// in NSS key log format that can be used to allow external programs
	// such as Wireshark to decrypt TLS connections.
	// See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format.
	// Use of KeyLogWriter compromises security and should only be
	// used for debugging.
	KeyLogWriter io.Writer
	// contains filtered or unexported fields
}

A Config structure is used to configure a TLS client or server. After one has been passed to a TLS function it must not be modified. A Config may be reused; the tls package will also not modify it.

Example (KeyLogWriter) 
Example (VerifyConnection) 

func (*Config)BuildNameToCertificateDEPRECATED

(*Config) Clone added in go1.8

func (c *Config) Clone() *Config

Clone returns a shallow clone of c or nil if c is nil. It is safe to clone a Config that is being used concurrently by a TLS client or server.

(*Config) SetSessionTicketKeys added in go1.5

func (c *Config) SetSessionTicketKeys(keys [][32]byte)

SetSessionTicketKeys updates the session ticket keys for a server.

The first key will be used when creating new tickets, while all keys can be used for decrypting tickets. It is safe to call this function while the server is running in order to rotate the session ticket keys. The function will panic if keys is empty.

Calling this function will turn off automatic session ticket key rotation.

If multiple servers are terminating connections for the same host they should all have the same session ticket keys. If the session ticket keys leaks, previously recorded and future TLS connections using those keys might be compromised.

type Conn

type Conn struct {
	// contains filtered or unexported fields
}

A Conn represents a secured connection. It implements the net.Conn interface.

func Client

func Client(conn net.Conn, config *Config) *Conn

Client returns a new TLS client side connection using conn as the underlying transport. The config cannot be nil: users must set either ServerName or InsecureSkipVerify in the config.

func Dial

func Dial(network, addr string, config *Config) (*Conn, error)

Dial connects to the given network address using net.Dial and then initiates a TLS handshake, returning the resulting TLS connection. Dial interprets a nil configuration as equivalent to the zero configuration; see the documentation of Config for the defaults.

Example 

func DialWithDialer added in go1.3

func DialWithDialer(dialer *net.Dialer, network, addr string, config *Config) (*Conn, error)

DialWithDialer connects to the given network address using dialer.Dial and then initiates a TLS handshake, returning the resulting TLS connection. Any timeout or deadline given in the dialer apply to connection and TLS handshake as a whole.

DialWithDialer interprets a nil configuration as equivalent to the zero configuration; see the documentation of Config for the defaults.

DialWithDialer uses context.Background internally; to specify the context, use Dialer.DialContext with NetDialer set to the desired dialer.

func Server

func Server(conn net.Conn, config *Config) *Conn

Server returns a new TLS server side connection using conn as the underlying transport. The configuration config must be non-nil and must include at least one certificate or else set GetCertificate.

(*Conn) Close

func (c *Conn) Close() error

Close closes the connection.

(*Conn) CloseWrite added in go1.8

func (c *Conn) CloseWrite() error

CloseWrite shuts down the writing side of the connection. It should only be called once the handshake has completed and does not call CloseWrite on the underlying connection. Most callers should just use Close.

(*Conn) ConnectionState

func (c *Conn) ConnectionState() ConnectionState

ConnectionState returns basic TLS details about the connection.

(*Conn) Handshake

func (c *Conn) Handshake() error

Handshake runs the client or server handshake protocol if it has not yet been run.

Most uses of this package need not call Handshake explicitly: the first Read or Write will call it automatically.

For control over canceling or setting a timeout on a handshake, use HandshakeContext or the Dialer’s DialContext method instead.

(*Conn) HandshakeContext added in go1.17

func (c *Conn) HandshakeContext(ctx context.Context) error

HandshakeContext runs the client or server handshake protocol if it has not yet been run.

The provided Context must be non-nil. If the context is canceled before the handshake is complete, the handshake is interrupted and an error is returned. Once the handshake has completed, cancellation of the context will not affect the connection.

Most uses of this package need not call HandshakeContext explicitly: the first Read or Write will call it automatically.

(*Conn) LocalAddr

func (c *Conn) LocalAddr() net.Addr

LocalAddr returns the local network address.

(*Conn) NetConn added in go1.18

func (c *Conn) NetConn() net.Conn

NetConn returns the underlying connection that is wrapped by c. Note that writing to or reading from this connection directly will corrupt the TLS session.

(*Conn) OCSPResponse

func (c *Conn) OCSPResponse() []byte

OCSPResponse returns the stapled OCSP response from the TLS server, if any. (Only valid for client connections.)

(*Conn) Read

func (c *Conn) Read(b []byte) (int, error)

Read reads data from the connection.

As Read calls Handshake, in order to prevent indefinite blocking a deadline must be set for both Read and Write before Read is called when the handshake has not yet completed. See SetDeadline, SetReadDeadline, and SetWriteDeadline.

(*Conn) RemoteAddr

func (c *Conn) RemoteAddr() net.Addr

RemoteAddr returns the remote network address.

(*Conn) SetDeadline

func (c *Conn) SetDeadline(t time.Time) error

SetDeadline sets the read and write deadlines associated with the connection. A zero value for t means Read and Write will not time out. After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.

(*Conn) SetReadDeadline

func (c *Conn) SetReadDeadline(t time.Time) error

SetReadDeadline sets the read deadline on the underlying connection. A zero value for t means Read will not time out.

(*Conn) SetWriteDeadline

func (c *Conn) SetWriteDeadline(t time.Time) error

SetWriteDeadline sets the write deadline on the underlying connection. A zero value for t means Write will not time out. After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.

(*Conn) VerifyHostname

func (c *Conn) VerifyHostname(host string) error

VerifyHostname checks that the peer certificate chain is valid for connecting to host. If so, it returns nil; if not, it returns an error describing the problem.

(*Conn) Write

func (c *Conn) Write(b []byte) (int, error)

Write writes data to the connection.

As Write calls Handshake, in order to prevent indefinite blocking a deadline must be set for both Read and Write before Write is called when the handshake has not yet completed. See SetDeadline, SetReadDeadline, and SetWriteDeadline.

type ConnectionState

type ConnectionState struct {
	// Version is the TLS version used by the connection (e.g. VersionTLS12).
	Version uint16

	// HandshakeComplete is true if the handshake has concluded.
	HandshakeComplete bool

	// DidResume is true if this connection was successfully resumed from a
	// previous session with a session ticket or similar mechanism.
	DidResume bool

	// CipherSuite is the cipher suite negotiated for the connection (e.g.
	// TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_AES_128_GCM_SHA256).
	CipherSuite uint16

	// NegotiatedProtocol is the application protocol negotiated with ALPN.
	NegotiatedProtocol string

	// NegotiatedProtocolIsMutual used to indicate a mutual NPN negotiation.
	//
	// Deprecated: this value is always true.
	NegotiatedProtocolIsMutual bool

	// ServerName is the value of the Server Name Indication extension sent by
	// the client. It's available both on the server and on the client side.
	ServerName string

	// PeerCertificates are the parsed certificates sent by the peer, in the
	// order in which they were sent. The first element is the leaf certificate
	// that the connection is verified against.
	//
	// On the client side, it can't be empty. On the server side, it can be
	// empty if Config.ClientAuth is not RequireAnyClientCert or
	// RequireAndVerifyClientCert.
	//
	// PeerCertificates and its contents should not be modified.
	PeerCertificates []*x509.Certificate

	// VerifiedChains is a list of one or more chains where the first element is
	// PeerCertificates[0] and the last element is from Config.RootCAs (on the
	// client side) or Config.ClientCAs (on the server side).
	//
	// On the client side, it's set if Config.InsecureSkipVerify is false. On
	// the server side, it's set if Config.ClientAuth is VerifyClientCertIfGiven
	// (and the peer provided a certificate) or RequireAndVerifyClientCert.
	//
	// VerifiedChains and its contents should not be modified.
	VerifiedChains [][]*x509.Certificate

	// SignedCertificateTimestamps is a list of SCTs provided by the peer
	// through the TLS handshake for the leaf certificate, if any.
	SignedCertificateTimestamps [][]byte

	// OCSPResponse is a stapled Online Certificate Status Protocol (OCSP)
	// response provided by the peer for the leaf certificate, if any.
	OCSPResponse []byte

	// TLSUnique contains the "tls-unique" channel binding value (see RFC 5929,
	// Section 3). This value will be nil for TLS 1.3 connections and for all
	// resumed connections.
	//
	// Deprecated: there are conditions in which this value might not be unique
	// to a connection. See the Security Considerations sections of RFC 5705 and
	// RFC 7627, and https://mitls.org/pages/attacks/3SHAKE#channelbindings.
	TLSUnique []byte
	// contains filtered or unexported fields
}

ConnectionState records basic TLS details about the connection.

(*ConnectionState) ExportKeyingMaterial added in go1.11

func (cs *ConnectionState) ExportKeyingMaterial(label string, context []byte, length int) ([]byte, error)

ExportKeyingMaterial returns length bytes of exported key material in a new slice as defined in RFC 5705. If context is nil, it is not used as part of the seed. If the connection was set to allow renegotiation via Config.Renegotiation, this function will return an error.

type CurveID added in go1.3

type CurveID uint16

CurveID is the type of a TLS identifier for an elliptic curve. See https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8.

In TLS 1.3, this type is called NamedGroup, but at this time this library only supports Elliptic Curve based groups. See RFC 8446, Section 4.2.7.

const (
	CurveP256 CurveID = 23
	CurveP384 CurveID = 24
	CurveP521 CurveID = 25
	X25519    CurveID = 29
)

(CurveID) String added in go1.15

func (i CurveID) String() string

type Dialer added in go1.15

type Dialer struct {
	// NetDialer is the optional dialer to use for the TLS connections'
	// underlying TCP connections.
	// A nil NetDialer is equivalent to the net.Dialer zero value.
	NetDialer *net.Dialer

	// Config is the TLS configuration to use for new connections.
	// A nil configuration is equivalent to the zero
	// configuration; see the documentation of Config for the
	// defaults.
	Config *Config
}

Dialer dials TLS connections given a configuration and a Dialer for the underlying connection.

(*Dialer) Dial added in go1.15

func (d *Dialer) Dial(network, addr string) (net.Conn, error)

Dial connects to the given network address and initiates a TLS handshake, returning the resulting TLS connection.

The returned Conn, if any, will always be of type *Conn.

Dial uses context.Background internally; to specify the context, use DialContext.

(*Dialer) DialContext added in go1.15

func (d *Dialer) DialContext(ctx context.Context, network, addr string) (net.Conn, error)

DialContext connects to the given network address and initiates a TLS handshake, returning the resulting TLS connection.

The provided Context must be non-nil. If the context expires before the connection is complete, an error is returned. Once successfully connected, any expiration of the context will not affect the connection.

The returned Conn, if any, will always be of type *Conn.

type RecordHeaderError added in go1.6

type RecordHeaderError struct {
	// Msg contains a human readable string that describes the error.
	Msg string
	// RecordHeader contains the five bytes of TLS record header that
	// triggered the error.
	RecordHeader [5]byte
	// Conn provides the underlying net.Conn in the case that a client
	// sent an initial handshake that didn't look like TLS.
	// It is nil if there's already been a handshake or a TLS alert has
	// been written to the connection.
	Conn net.Conn
}

RecordHeaderError is returned when a TLS record header is invalid.

(RecordHeaderError) Error added in go1.6

func (e RecordHeaderError) Error() string

type RenegotiationSupport added in go1.7

type RenegotiationSupport int

RenegotiationSupport enumerates the different levels of support for TLS renegotiation. TLS renegotiation is the act of performing subsequent handshakes on a connection after the first. This significantly complicates the state machine and has been the source of numerous, subtle security issues. Initiating a renegotiation is not supported, but support for accepting renegotiation requests may be enabled.

Even when enabled, the server may not change its identity between handshakes (i.e. the leaf certificate must be the same). Additionally, concurrent handshake and application data flow is not permitted so renegotiation can only be used with protocols that synchronise with the renegotiation, such as HTTPS.

Renegotiation is not defined in TLS 1.3.

const (
	// RenegotiateNever disables renegotiation.
	RenegotiateNever RenegotiationSupport = iota

	// RenegotiateOnceAsClient allows a remote server to request
	// renegotiation once per connection.
	RenegotiateOnceAsClient

	// RenegotiateFreelyAsClient allows a remote server to repeatedly
	// request renegotiation.
	RenegotiateFreelyAsClient
)

type SignatureScheme added in go1.8

type SignatureScheme uint16

SignatureScheme identifies a signature algorithm supported by TLS. See RFC 8446, Section 4.2.3.

const (
	// RSASSA-PKCS1-v1_5 algorithms.
	PKCS1WithSHA256 SignatureScheme = 0x0401
	PKCS1WithSHA384 SignatureScheme = 0x0501
	PKCS1WithSHA512 SignatureScheme = 0x0601

	// RSASSA-PSS algorithms with public key OID rsaEncryption.
	PSSWithSHA256 SignatureScheme = 0x0804
	PSSWithSHA384 SignatureScheme = 0x0805
	PSSWithSHA512 SignatureScheme = 0x0806

	// ECDSA algorithms. Only constrained to a specific curve in TLS 1.3.
	ECDSAWithP256AndSHA256 SignatureScheme = 0x0403
	ECDSAWithP384AndSHA384 SignatureScheme = 0x0503
	ECDSAWithP521AndSHA512 SignatureScheme = 0x0603

	// EdDSA algorithms.
	Ed25519 SignatureScheme = 0x0807

	// Legacy signature and hash algorithms for TLS 1.2.
	PKCS1WithSHA1 SignatureScheme = 0x0201
	ECDSAWithSHA1 SignatureScheme = 0x0203
)

(SignatureScheme) String added in go1.15

func (i SignatureScheme) String() string

Notes

Bugs

4.20 - x509

x509

https://pkg.go.dev/crypto/x509@go1.20.1

Package x509 implements a subset of the X.509 standard.

It allows parsing and generating certificates, certificate signing requests, certificate revocation lists, and encoded public and private keys. It provides a certificate verifier, complete with a chain builder.

The package targets the X.509 technical profile defined by the IETF (RFC 2459/3280/5280), and as further restricted by the CA/Browser Forum Baseline Requirements. There is minimal support for features outside of these profiles, as the primary goal of the package is to provide compatibility with the publicly trusted TLS certificate ecosystem and its policies and constraints.

On macOS and Windows, certificate verification is handled by system APIs, but the package aims to apply consistent validation rules across operating systems.

常量

This section is empty.

变量

View Source

var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented")

ErrUnsupportedAlgorithm results from attempting to perform an operation that involves algorithms that are not currently implemented.

View Source

var IncorrectPasswordError = errors.New("x509: decryption password incorrect")

IncorrectPasswordError is returned when an incorrect password is detected.

函数

func CreateCertificate

func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv any) ([]byte, error)

CreateCertificate creates a new X.509 v3 certificate based on a template. The following members of template are currently used:

  • AuthorityKeyId
  • BasicConstraintsValid
  • CRLDistributionPoints
  • DNSNames
  • EmailAddresses
  • ExcludedDNSDomains
  • ExcludedEmailAddresses
  • ExcludedIPRanges
  • ExcludedURIDomains
  • ExtKeyUsage
  • ExtraExtensions
  • IPAddresses
  • IsCA
  • IssuingCertificateURL
  • KeyUsage
  • MaxPathLen
  • MaxPathLenZero
  • NotAfter
  • NotBefore
  • OCSPServer
  • PermittedDNSDomains
  • PermittedDNSDomainsCritical
  • PermittedEmailAddresses
  • PermittedIPRanges
  • PermittedURIDomains
  • PolicyIdentifiers
  • SerialNumber
  • SignatureAlgorithm
  • Subject
  • SubjectKeyId
  • URIs
  • UnknownExtKeyUsage

The certificate is signed by parent. If parent is equal to template then the certificate is self-signed. The parameter pub is the public key of the certificate to be generated and priv is the private key of the signer.

The returned slice is the certificate in DER encoding.

The currently supported key types are *rsa.PublicKey, *ecdsa.PublicKey and ed25519.PublicKey. pub must be a supported key type, and priv must be a crypto.Signer with a supported public key.

The AuthorityKeyId will be taken from the SubjectKeyId of parent, if any, unless the resulting certificate is self-signed. Otherwise the value from template will be used.

If SubjectKeyId from template is empty and the template is a CA, SubjectKeyId will be generated from the hash of the public key.

func CreateCertificateRequest added in go1.3

func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv any) (csr []byte, err error)

CreateCertificateRequest creates a new certificate request based on a template. The following members of template are used:

  • SignatureAlgorithm
  • Subject
  • DNSNames
  • EmailAddresses
  • IPAddresses
  • URIs
  • ExtraExtensions
  • Attributes (deprecated)

priv is the private key to sign the CSR with, and the corresponding public key will be included in the CSR. It must implement crypto.Signer and its Public() method must return a *rsa.PublicKey or a *ecdsa.PublicKey or a ed25519.PublicKey. (A *rsa.PrivateKey, *ecdsa.PrivateKey or ed25519.PrivateKey satisfies this.)

The returned slice is the certificate request in DER encoding.

func CreateRevocationList added in go1.15

func CreateRevocationList(rand io.Reader, template *RevocationList, issuer *Certificate, priv crypto.Signer) ([]byte, error)

CreateRevocationList creates a new X.509 v2 Certificate Revocation List, according to RFC 5280, based on template.

The CRL is signed by priv which should be the private key associated with the public key in the issuer certificate.

The issuer may not be nil, and the crlSign bit must be set in KeyUsage in order to use it as a CRL issuer.

The issuer distinguished name CRL field and authority key identifier extension are populated using the issuer certificate. issuer must have SubjectKeyId set.

funcDecryptPEMBlockDEPRECATEDadded in go1.1

funcEncryptPEMBlockDEPRECATEDadded in go1.1

funcIsEncryptedPEMBlockDEPRECATEDadded in go1.1

func MarshalECPrivateKey added in go1.2

func MarshalECPrivateKey(key *ecdsa.PrivateKey) ([]byte, error)

MarshalECPrivateKey converts an EC private key to SEC 1, ASN.1 DER form.

This kind of key is commonly encoded in PEM blocks of type “EC PRIVATE KEY”. For a more flexible key format which is not EC specific, use MarshalPKCS8PrivateKey.

func MarshalPKCS1PrivateKey

func MarshalPKCS1PrivateKey(key *rsa.PrivateKey) []byte

MarshalPKCS1PrivateKey converts an RSA private key to PKCS #1, ASN.1 DER form.

This kind of key is commonly encoded in PEM blocks of type “RSA PRIVATE KEY”. For a more flexible key format which is not RSA specific, use MarshalPKCS8PrivateKey.

func MarshalPKCS1PublicKey added in go1.10

func MarshalPKCS1PublicKey(key *rsa.PublicKey) []byte

MarshalPKCS1PublicKey converts an RSA public key to PKCS #1, ASN.1 DER form.

This kind of key is commonly encoded in PEM blocks of type “RSA PUBLIC KEY”.

func MarshalPKCS8PrivateKey added in go1.10

func MarshalPKCS8PrivateKey(key any) ([]byte, error)

MarshalPKCS8PrivateKey converts a private key to PKCS #8, ASN.1 DER form.

The following key types are currently supported: *rsa.PrivateKey, *ecdsa.PrivateKey, ed25519.PrivateKey (not a pointer), and *ecdh.PrivateKey. Unsupported key types result in an error.

This kind of key is commonly encoded in PEM blocks of type “PRIVATE KEY”.

func MarshalPKIXPublicKey

func MarshalPKIXPublicKey(pub any) ([]byte, error)

MarshalPKIXPublicKey converts a public key to PKIX, ASN.1 DER form. The encoded public key is a SubjectPublicKeyInfo structure (see RFC 5280, Section 4.1).

The following key types are currently supported: *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey (not a pointer), and *ecdh.PublicKey. Unsupported key types result in an error.

This kind of key is commonly encoded in PEM blocks of type “PUBLIC KEY”.

funcParseCRLDEPRECATED

funcParseDERCRLDEPRECATED

func ParseECPrivateKey added in go1.1

func ParseECPrivateKey(der []byte) (*ecdsa.PrivateKey, error)

ParseECPrivateKey parses an EC private key in SEC 1, ASN.1 DER form.

This kind of key is commonly encoded in PEM blocks of type “EC PRIVATE KEY”.

func ParsePKCS1PrivateKey

func ParsePKCS1PrivateKey(der []byte) (*rsa.PrivateKey, error)

ParsePKCS1PrivateKey parses an RSA private key in PKCS #1, ASN.1 DER form.

This kind of key is commonly encoded in PEM blocks of type “RSA PRIVATE KEY”.

func ParsePKCS1PublicKey added in go1.10

func ParsePKCS1PublicKey(der []byte) (*rsa.PublicKey, error)

ParsePKCS1PublicKey parses an RSA public key in PKCS #1, ASN.1 DER form.

This kind of key is commonly encoded in PEM blocks of type “RSA PUBLIC KEY”.

func ParsePKCS8PrivateKey

func ParsePKCS8PrivateKey(der []byte) (key any, err error)

ParsePKCS8PrivateKey parses an unencrypted private key in PKCS #8, ASN.1 DER form.

It returns a *rsa.PrivateKey, a *ecdsa.PrivateKey, a ed25519.PrivateKey (not a pointer), or a *ecdh.PublicKey (for X25519). More types might be supported in the future.

This kind of key is commonly encoded in PEM blocks of type “PRIVATE KEY”.

func ParsePKIXPublicKey

func ParsePKIXPublicKey(derBytes []byte) (pub any, err error)

ParsePKIXPublicKey parses a public key in PKIX, ASN.1 DER form. The encoded public key is a SubjectPublicKeyInfo structure (see RFC 5280, Section 4.1).

It returns a *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey (not a pointer), or *ecdh.PublicKey (for X25519). More types might be supported in the future.

This kind of key is commonly encoded in PEM blocks of type “PUBLIC KEY”.

Example 

func SetFallbackRoots added in go1.20

func SetFallbackRoots(roots *CertPool)

SetFallbackRoots sets the roots to use during certificate verification, if no custom roots are specified and a platform verifier or a system certificate pool is not available (for instance in a container which does not have a root certificate bundle). SetFallbackRoots will panic if roots is nil.

SetFallbackRoots may only be called once, if called multiple times it will panic.

The fallback behavior can be forced on all platforms, even when there is a system certificate pool, by setting GODEBUG=x509usefallbackroots=1 (note that on Windows and macOS this will disable usage of the platform verification APIs and cause the pure Go verifier to be used). Setting x509usefallbackroots=1 without calling SetFallbackRoots has no effect.

类型

type CertPool

type CertPool struct {
	// contains filtered or unexported fields
}

CertPool is a set of certificates.

func NewCertPool

func NewCertPool() *CertPool

NewCertPool returns a new, empty CertPool.

func SystemCertPool added in go1.7

func SystemCertPool() (*CertPool, error)

SystemCertPool returns a copy of the system cert pool.

On Unix systems other than macOS the environment variables SSL_CERT_FILE and SSL_CERT_DIR can be used to override the system default locations for the SSL certificate file and SSL certificate files directory, respectively. The latter can be a colon-separated list.

Any mutations to the returned pool are not written to disk and do not affect any other pool returned by SystemCertPool.

New changes in the system cert pool might not be reflected in subsequent calls.

(*CertPool) AddCert

func (s *CertPool) AddCert(cert *Certificate)

AddCert adds a certificate to a pool.

(*CertPool) AppendCertsFromPEM

func (s *CertPool) AppendCertsFromPEM(pemCerts []byte) (ok bool)

AppendCertsFromPEM attempts to parse a series of PEM encoded certificates. It appends any certificates found to s and reports whether any certificates were successfully parsed.

On many Linux systems, /etc/ssl/cert.pem will contain the system wide set of root CAs in a format suitable for this function.

(*CertPool) Clone added in go1.19

func (s *CertPool) Clone() *CertPool

Clone returns a copy of s.

(*CertPool) Equal added in go1.19

func (s *CertPool) Equal(other *CertPool) bool

Equal reports whether s and other are equal.

func (*CertPool)SubjectsDEPRECATED

type Certificate

type Certificate struct {
	Raw                     []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature).
	RawTBSCertificate       []byte // Certificate part of raw ASN.1 DER content.
	RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
	RawSubject              []byte // DER encoded Subject
	RawIssuer               []byte // DER encoded Issuer

	Signature          []byte
	SignatureAlgorithm SignatureAlgorithm

	PublicKeyAlgorithm PublicKeyAlgorithm
	PublicKey          any

	Version             int
	SerialNumber        *big.Int
	Issuer              pkix.Name
	Subject             pkix.Name
	NotBefore, NotAfter time.Time // Validity bounds.
	KeyUsage            KeyUsage

	// Extensions contains raw X.509 extensions. When parsing certificates,
	// this can be used to extract non-critical extensions that are not
	// parsed by this package. When marshaling certificates, the Extensions
	// field is ignored, see ExtraExtensions.
	Extensions []pkix.Extension

	// ExtraExtensions contains extensions to be copied, raw, into any
	// marshaled certificates. Values override any extensions that would
	// otherwise be produced based on the other fields. The ExtraExtensions
	// field is not populated when parsing certificates, see Extensions.
	ExtraExtensions []pkix.Extension

	// UnhandledCriticalExtensions contains a list of extension IDs that
	// were not (fully) processed when parsing. Verify will fail if this
	// slice is non-empty, unless verification is delegated to an OS
	// library which understands all the critical extensions.
	//
	// Users can access these extensions using Extensions and can remove
	// elements from this slice if they believe that they have been
	// handled.
	UnhandledCriticalExtensions []asn1.ObjectIdentifier

	ExtKeyUsage        []ExtKeyUsage           // Sequence of extended key usages.
	UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package.

	// BasicConstraintsValid indicates whether IsCA, MaxPathLen,
	// and MaxPathLenZero are valid.
	BasicConstraintsValid bool
	IsCA                  bool

	// MaxPathLen and MaxPathLenZero indicate the presence and
	// value of the BasicConstraints' "pathLenConstraint".
	//
	// When parsing a certificate, a positive non-zero MaxPathLen
	// means that the field was specified, -1 means it was unset,
	// and MaxPathLenZero being true mean that the field was
	// explicitly set to zero. The case of MaxPathLen==0 with MaxPathLenZero==false
	// should be treated equivalent to -1 (unset).
	//
	// When generating a certificate, an unset pathLenConstraint
	// can be requested with either MaxPathLen == -1 or using the
	// zero value for both MaxPathLen and MaxPathLenZero.
	MaxPathLen int
	// MaxPathLenZero indicates that BasicConstraintsValid==true
	// and MaxPathLen==0 should be interpreted as an actual
	// maximum path length of zero. Otherwise, that combination is
	// interpreted as MaxPathLen not being set.
	MaxPathLenZero bool

	SubjectKeyId   []byte
	AuthorityKeyId []byte

	// RFC 5280, 4.2.2.1 (Authority Information Access)
	OCSPServer            []string
	IssuingCertificateURL []string

	// Subject Alternate Name values. (Note that these values may not be valid
	// if invalid values were contained within a parsed certificate. For
	// example, an element of DNSNames may not be a valid DNS domain name.)
	DNSNames       []string
	EmailAddresses []string
	IPAddresses    []net.IP
	URIs           []*url.URL

	// Name constraints
	PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical.
	PermittedDNSDomains         []string
	ExcludedDNSDomains          []string
	PermittedIPRanges           []*net.IPNet
	ExcludedIPRanges            []*net.IPNet
	PermittedEmailAddresses     []string
	ExcludedEmailAddresses      []string
	PermittedURIDomains         []string
	ExcludedURIDomains          []string

	// CRL Distribution Points
	CRLDistributionPoints []string

	PolicyIdentifiers []asn1.ObjectIdentifier
}

A Certificate represents an X.509 certificate.

func ParseCertificate

func ParseCertificate(der []byte) (*Certificate, error)

ParseCertificate parses a single certificate from the given ASN.1 DER data.

func ParseCertificates

func ParseCertificates(der []byte) ([]*Certificate, error)

ParseCertificates parses one or more certificates from the given ASN.1 DER data. The certificates must be concatenated with no intermediate padding.

func (*Certificate)CheckCRLSignatureDEPRECATED

(*Certificate) CheckSignature

func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error

CheckSignature verifies that signature is a valid signature over signed from c’s public key.

This is a low-level API that performs no validity checks on the certificate.

MD5WithRSA signatures are rejected, while SHA1WithRSA and ECDSAWithSHA1 signatures are currently accepted.

(*Certificate) CheckSignatureFrom

func (c *Certificate) CheckSignatureFrom(parent *Certificate) error

CheckSignatureFrom verifies that the signature on c is a valid signature from parent.

This is a low-level API that performs very limited checks, and not a full path verifier. Most users should use Certificate.Verify instead.

func (*Certificate)CreateCRLDEPRECATED

(*Certificate) Equal

func (c *Certificate) Equal(other *Certificate) bool

(*Certificate) Verify

func (c *Certificate) Verify(opts VerifyOptions) (chains [][]*Certificate, err error)

Verify attempts to verify c by building one or more chains from c to a certificate in opts.Roots, using certificates in opts.Intermediates if needed. If successful, it returns one or more chains where the first element of the chain is c and the last element is from opts.Roots.

If opts.Roots is nil, the platform verifier might be used, and verification details might differ from what is described below. If system roots are unavailable the returned error will be of type SystemRootsError.

Name constraints in the intermediates will be applied to all names claimed in the chain, not just opts.DNSName. Thus it is invalid for a leaf to claim example.com if an intermediate doesn’t permit it, even if example.com is not the name being validated. Note that DirectoryName constraints are not supported.

Name constraint validation follows the rules from RFC 5280, with the addition that DNS name constraints may use the leading period format defined for emails and URIs. When a constraint has a leading period it indicates that at least one additional label must be prepended to the constrained name to be considered valid.

Extended Key Usage values are enforced nested down a chain, so an intermediate or root that enumerates EKUs prevents a leaf from asserting an EKU not in that list. (While this is not specified, it is common practice in order to limit the types of certificates a CA can issue.)

Certificates that use SHA1WithRSA and ECDSAWithSHA1 signatures are not supported, and will not be used to build chains.

Certificates other than c in the returned chains should not be modified.

WARNING: this function doesn’t do any revocation checking.

Example 

(*Certificate) VerifyHostname

func (c *Certificate) VerifyHostname(h string) error

VerifyHostname returns nil if c is a valid certificate for the named host. Otherwise it returns an error describing the mismatch.

IP addresses can be optionally enclosed in square brackets and are checked against the IPAddresses field. Other names are checked case insensitively against the DNSNames field. If the names are valid hostnames, the certificate fields can have a wildcard as the left-most label.

Note that the legacy Common Name field is ignored.

type CertificateInvalidError

type CertificateInvalidError struct {
	Cert   *Certificate
	Reason InvalidReason
	Detail string
}

CertificateInvalidError results when an odd error occurs. Users of this library probably want to handle all these errors uniformly.

(CertificateInvalidError) Error

func (e CertificateInvalidError) Error() string

type CertificateRequest added in go1.3

type CertificateRequest struct {
	Raw                      []byte // Complete ASN.1 DER content (CSR, signature algorithm and signature).
	RawTBSCertificateRequest []byte // Certificate request info part of raw ASN.1 DER content.
	RawSubjectPublicKeyInfo  []byte // DER encoded SubjectPublicKeyInfo.
	RawSubject               []byte // DER encoded Subject.

	Version            int
	Signature          []byte
	SignatureAlgorithm SignatureAlgorithm

	PublicKeyAlgorithm PublicKeyAlgorithm
	PublicKey          any

	Subject pkix.Name

	// Attributes contains the CSR attributes that can parse as
	// pkix.AttributeTypeAndValueSET.
	//
	// Deprecated: Use Extensions and ExtraExtensions instead for parsing and
	// generating the requestedExtensions attribute.
	Attributes []pkix.AttributeTypeAndValueSET

	// Extensions contains all requested extensions, in raw form. When parsing
	// CSRs, this can be used to extract extensions that are not parsed by this
	// package.
	Extensions []pkix.Extension

	// ExtraExtensions contains extensions to be copied, raw, into any CSR
	// marshaled by CreateCertificateRequest. Values override any extensions
	// that would otherwise be produced based on the other fields but are
	// overridden by any extensions specified in Attributes.
	//
	// The ExtraExtensions field is not populated by ParseCertificateRequest,
	// see Extensions instead.
	ExtraExtensions []pkix.Extension

	// Subject Alternate Name values.
	DNSNames       []string
	EmailAddresses []string
	IPAddresses    []net.IP
	URIs           []*url.URL
}

CertificateRequest represents a PKCS #10, certificate signature request.

func ParseCertificateRequest added in go1.3

func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error)

ParseCertificateRequest parses a single certificate request from the given ASN.1 DER data.

(*CertificateRequest) CheckSignature added in go1.5

func (c *CertificateRequest) CheckSignature() error

CheckSignature reports whether the signature on c is valid.

type ConstraintViolationError

type ConstraintViolationError struct{}

ConstraintViolationError results when a requested usage is not permitted by a certificate. For example: checking a signature when the public key isn’t a certificate signing key.

(ConstraintViolationError) Error

func (ConstraintViolationError) Error() string

type ExtKeyUsage

type ExtKeyUsage int

ExtKeyUsage represents an extended set of actions that are valid for a given key. Each of the ExtKeyUsage* constants define a unique action.

const (
	ExtKeyUsageAny ExtKeyUsage = iota
	ExtKeyUsageServerAuth
	ExtKeyUsageClientAuth
	ExtKeyUsageCodeSigning
	ExtKeyUsageEmailProtection
	ExtKeyUsageIPSECEndSystem
	ExtKeyUsageIPSECTunnel
	ExtKeyUsageIPSECUser
	ExtKeyUsageTimeStamping
	ExtKeyUsageOCSPSigning
	ExtKeyUsageMicrosoftServerGatedCrypto
	ExtKeyUsageNetscapeServerGatedCrypto
	ExtKeyUsageMicrosoftCommercialCodeSigning
	ExtKeyUsageMicrosoftKernelCodeSigning
)

type HostnameError

type HostnameError struct {
	Certificate *Certificate
	Host        string
}

HostnameError results when the set of authorized names doesn’t match the requested name.

(HostnameError) Error

func (h HostnameError) Error() string

type InsecureAlgorithmError added in go1.6

type InsecureAlgorithmError SignatureAlgorithm

An InsecureAlgorithmError indicates that the SignatureAlgorithm used to generate the signature is not secure, and the signature has been rejected.

To temporarily restore support for SHA-1 signatures, include the value “x509sha1=1” in the GODEBUG environment variable. Note that this option will be removed in a future release.

(InsecureAlgorithmError) Error added in go1.6

func (e InsecureAlgorithmError) Error() string

type InvalidReason

type InvalidReason int
const (
	// NotAuthorizedToSign results when a certificate is signed by another
	// which isn't marked as a CA certificate.
	NotAuthorizedToSign InvalidReason = iota
	// Expired results when a certificate has expired, based on the time
	// given in the VerifyOptions.
	Expired
	// CANotAuthorizedForThisName results when an intermediate or root
	// certificate has a name constraint which doesn't permit a DNS or
	// other name (including IP address) in the leaf certificate.
	CANotAuthorizedForThisName
	// TooManyIntermediates results when a path length constraint is
	// violated.
	TooManyIntermediates
	// IncompatibleUsage results when the certificate's key usage indicates
	// that it may only be used for a different purpose.
	IncompatibleUsage
	// NameMismatch results when the subject name of a parent certificate
	// does not match the issuer name in the child.
	NameMismatch
	// NameConstraintsWithoutSANs is a legacy error and is no longer returned.
	NameConstraintsWithoutSANs
	// UnconstrainedName results when a CA certificate contains permitted
	// name constraints, but leaf certificate contains a name of an
	// unsupported or unconstrained type.
	UnconstrainedName
	// TooManyConstraints results when the number of comparison operations
	// needed to check a certificate exceeds the limit set by
	// VerifyOptions.MaxConstraintComparisions. This limit exists to
	// prevent pathological certificates can consuming excessive amounts of
	// CPU time to verify.
	TooManyConstraints
	// CANotAuthorizedForExtKeyUsage results when an intermediate or root
	// certificate does not permit a requested extended key usage.
	CANotAuthorizedForExtKeyUsage
)

type KeyUsage

type KeyUsage int

KeyUsage represents the set of actions that are valid for a given key. It’s a bitmap of the KeyUsage* constants.

const (
	KeyUsageDigitalSignature KeyUsage = 1 << iota
	KeyUsageContentCommitment
	KeyUsageKeyEncipherment
	KeyUsageDataEncipherment
	KeyUsageKeyAgreement
	KeyUsageCertSign
	KeyUsageCRLSign
	KeyUsageEncipherOnly
	KeyUsageDecipherOnly
)

type PEMCipher added in go1.1

type PEMCipher int
const (
	PEMCipherDES PEMCipher
	PEMCipher3DES
	PEMCipherAES128
	PEMCipherAES192
	PEMCipherAES256
)

Possible values for the EncryptPEMBlock encryption algorithm.

type PublicKeyAlgorithm

type PublicKeyAlgorithm int
const (
	UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
	RSA
	DSA // Only supported for parsing.
	ECDSA
	Ed25519
)

(PublicKeyAlgorithm) String added in go1.10

func (algo PublicKeyAlgorithm) String() string

type RevocationList added in go1.15

type RevocationList struct {
	// Raw contains the complete ASN.1 DER content of the CRL (tbsCertList,
	// signatureAlgorithm, and signatureValue.)
	Raw []byte
	// RawTBSRevocationList contains just the tbsCertList portion of the ASN.1
	// DER.
	RawTBSRevocationList []byte
	// RawIssuer contains the DER encoded Issuer.
	RawIssuer []byte

	// Issuer contains the DN of the issuing certificate.
	Issuer pkix.Name
	// AuthorityKeyId is used to identify the public key associated with the
	// issuing certificate. It is populated from the authorityKeyIdentifier
	// extension when parsing a CRL. It is ignored when creating a CRL; the
	// extension is populated from the issuing certificate itself.
	AuthorityKeyId []byte

	Signature []byte
	// SignatureAlgorithm is used to determine the signature algorithm to be
	// used when signing the CRL. If 0 the default algorithm for the signing
	// key will be used.
	SignatureAlgorithm SignatureAlgorithm

	// RevokedCertificates is used to populate the revokedCertificates
	// sequence in the CRL, it may be empty. RevokedCertificates may be nil,
	// in which case an empty CRL will be created.
	RevokedCertificates []pkix.RevokedCertificate

	// Number is used to populate the X.509 v2 cRLNumber extension in the CRL,
	// which should be a monotonically increasing sequence number for a given
	// CRL scope and CRL issuer. It is also populated from the cRLNumber
	// extension when parsing a CRL.
	Number *big.Int

	// ThisUpdate is used to populate the thisUpdate field in the CRL, which
	// indicates the issuance date of the CRL.
	ThisUpdate time.Time
	// NextUpdate is used to populate the nextUpdate field in the CRL, which
	// indicates the date by which the next CRL will be issued. NextUpdate
	// must be greater than ThisUpdate.
	NextUpdate time.Time

	// Extensions contains raw X.509 extensions. When creating a CRL,
	// the Extensions field is ignored, see ExtraExtensions.
	Extensions []pkix.Extension

	// ExtraExtensions contains any additional extensions to add directly to
	// the CRL.
	ExtraExtensions []pkix.Extension
}

RevocationList contains the fields used to create an X.509 v2 Certificate Revocation list with CreateRevocationList.

func ParseRevocationList added in go1.19

func ParseRevocationList(der []byte) (*RevocationList, error)

ParseRevocationList parses a X509 v2 Certificate Revocation List from the given ASN.1 DER data.

(*RevocationList) CheckSignatureFrom added in go1.19

func (rl *RevocationList) CheckSignatureFrom(parent *Certificate) error

CheckSignatureFrom verifies that the signature on rl is a valid signature from issuer.

type SignatureAlgorithm

type SignatureAlgorithm int
const (
	UnknownSignatureAlgorithm SignatureAlgorithm = iota

	MD2WithRSA  // Unsupported.
	MD5WithRSA  // Only supported for signing, not verification.
	SHA1WithRSA // Only supported for signing, and verification of CRLs, CSRs, and OCSP responses.
	SHA256WithRSA
	SHA384WithRSA
	SHA512WithRSA
	DSAWithSHA1   // Unsupported.
	DSAWithSHA256 // Unsupported.
	ECDSAWithSHA1 // Only supported for signing, and verification of CRLs, CSRs, and OCSP responses.
	ECDSAWithSHA256
	ECDSAWithSHA384
	ECDSAWithSHA512
	SHA256WithRSAPSS
	SHA384WithRSAPSS
	SHA512WithRSAPSS
	PureEd25519
)

(SignatureAlgorithm) String added in go1.6

func (algo SignatureAlgorithm) String() string

type SystemRootsError added in go1.1

type SystemRootsError struct {
	Err error
}

SystemRootsError results when we fail to load the system root certificates.

(SystemRootsError) Error added in go1.1

func (se SystemRootsError) Error() string

(SystemRootsError) Unwrap added in go1.16

func (se SystemRootsError) Unwrap() error

type UnhandledCriticalExtension

type UnhandledCriticalExtension struct{}

(UnhandledCriticalExtension) Error

func (h UnhandledCriticalExtension) Error() string

type UnknownAuthorityError

type UnknownAuthorityError struct {
	Cert *Certificate
	// contains filtered or unexported fields
}

UnknownAuthorityError results when the certificate issuer is unknown

(UnknownAuthorityError) Error

func (e UnknownAuthorityError) Error() string

type VerifyOptions

type VerifyOptions struct {
	// DNSName, if set, is checked against the leaf certificate with
	// Certificate.VerifyHostname or the platform verifier.
	DNSName string

	// Intermediates is an optional pool of certificates that are not trust
	// anchors, but can be used to form a chain from the leaf certificate to a
	// root certificate.
	Intermediates *CertPool
	// Roots is the set of trusted root certificates the leaf certificate needs
	// to chain up to. If nil, the system roots or the platform verifier are used.
	Roots *CertPool

	// CurrentTime is used to check the validity of all certificates in the
	// chain. If zero, the current time is used.
	CurrentTime time.Time

	// KeyUsages specifies which Extended Key Usage values are acceptable. A
	// chain is accepted if it allows any of the listed values. An empty list
	// means ExtKeyUsageServerAuth. To accept any key usage, include ExtKeyUsageAny.
	KeyUsages []ExtKeyUsage

	// MaxConstraintComparisions is the maximum number of comparisons to
	// perform when checking a given certificate's name constraints. If
	// zero, a sensible default is used. This limit prevents pathological
	// certificates from consuming excessive amounts of CPU time when
	// validating. It does not apply to the platform verifier.
	MaxConstraintComparisions int
}

VerifyOptions contains parameters for Certificate.Verify.

4.21 - x509/pkix

pkix

https://pkg.go.dev/crypto/x509/pkix@go1.20.1

Package pkix contains shared, low level structures used for ASN.1 parsing and serialization of X.509 certificates, CRL and OCSP.

常量

This section is empty.

变量

This section is empty.

函数

This section is empty.

类型

type AlgorithmIdentifier

type AlgorithmIdentifier struct {
	Algorithm  asn1.ObjectIdentifier
	Parameters asn1.RawValue `asn1:"optional"`
}

AlgorithmIdentifier represents the ASN.1 structure of the same name. See RFC 5280, section 4.1.1.2.

type AttributeTypeAndValue

type AttributeTypeAndValue struct {
	Type  asn1.ObjectIdentifier
	Value any
}

AttributeTypeAndValue mirrors the ASN.1 structure of the same name in RFC 5280, Section 4.1.2.4.

type AttributeTypeAndValueSET added in go1.3

type AttributeTypeAndValueSET struct {
	Type  asn1.ObjectIdentifier
	Value [][]AttributeTypeAndValue `asn1:"set"`
}

AttributeTypeAndValueSET represents a set of ASN.1 sequences of AttributeTypeAndValue sequences from RFC 2986 (PKCS #10).

typeCertificateListDEPRECATED

type Extension

type Extension struct {
	Id       asn1.ObjectIdentifier
	Critical bool `asn1:"optional"`
	Value    []byte
}

Extension represents the ASN.1 structure of the same name. See RFC 5280, section 4.2.

type Name

type Name struct {
	Country, Organization, OrganizationalUnit []string
	Locality, Province                        []string
	StreetAddress, PostalCode                 []string
	SerialNumber, CommonName                  string

	// Names contains all parsed attributes. When parsing distinguished names,
	// this can be used to extract non-standard attributes that are not parsed
	// by this package. When marshaling to RDNSequences, the Names field is
	// ignored, see ExtraNames.
	Names []AttributeTypeAndValue

	// ExtraNames contains attributes to be copied, raw, into any marshaled
	// distinguished names. Values override any attributes with the same OID.
	// The ExtraNames field is not populated when parsing, see Names.
	ExtraNames []AttributeTypeAndValue
}

Name represents an X.509 distinguished name. This only includes the common elements of a DN. Note that Name is only an approximation of the X.509 structure. If an accurate representation is needed, asn1.Unmarshal the raw subject or issuer as an RDNSequence.

(*Name) FillFromRDNSequence

func (n *Name) FillFromRDNSequence(rdns *RDNSequence)

FillFromRDNSequence populates n from the provided RDNSequence. Multi-entry RDNs are flattened, all entries are added to the relevant n fields, and the grouping is not preserved.

(Name) String added in go1.10

func (n Name) String() string

String returns the string form of n, roughly following the RFC 2253 Distinguished Names syntax.

(Name) ToRDNSequence

func (n Name) ToRDNSequence() (ret RDNSequence)

ToRDNSequence converts n into a single RDNSequence. The following attributes are encoded as multi-value RDNs:

  • Country
  • Organization
  • OrganizationalUnit
  • Locality
  • Province
  • StreetAddress
  • PostalCode

Each ExtraNames entry is encoded as an individual RDN.

type RDNSequence

type RDNSequence []RelativeDistinguishedNameSET

(RDNSequence) String added in go1.10

func (r RDNSequence) String() string

String returns a string representation of the sequence r, roughly following the RFC 2253 Distinguished Names syntax.

type RelativeDistinguishedNameSET

type RelativeDistinguishedNameSET []AttributeTypeAndValue

type RevokedCertificate

type RevokedCertificate struct {
	SerialNumber   *big.Int
	RevocationTime time.Time
	Extensions     []Extension `asn1:"optional"`
}

RevokedCertificate represents the ASN.1 structure of the same name. See RFC 5280, section 5.1.

5 - database

5.1 - sql

sql

https://pkg.go.dev/database/sql@go1.20.1

​ sql包提供了一个围绕SQL(或类SQL)数据库的通用接口。

​ sql包必须与数据库驱动程序一起使用。参见https://golang.org/s/sqldrivers,获取驱动程序的列表。

​ 不支持上下文取消的驱动程序将等到查询完成后才会返回。

​ 关于用法的例子,请参见wiki页面https://golang.org/s/sqlwiki

Example (OpenDBCLI)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package main

import (
	"context"
	"database/sql"
	"flag"
	"log"
	"os"
	"os/signal"
	"time"
)

var pool *sql.DB // 数据库连接池。

func main() {
	id := flag.Int64("id", 0, "person ID to find")
	dsn := flag.String("dsn", os.Getenv("DSN"), "connection data source name")
	flag.Parse()

	if len(*dsn) == 0 {
		log.Fatal("missing dsn flag")
	}
	if *id == 0 {
		log.Fatal("missing person ID")
	}
	var err error

   // 打开一个驱动程序通常不会尝试连接到数据库。
	pool, err = sql.Open("driver-name", *dsn)
	if err != nil {
       // 这将不是一个连接错误,而是一个DSN解析错误或其他初始化错误。
		log.Fatal("unable to use data source name", err)
	}
	defer pool.Close()

	pool.SetConnMaxLifetime(0)
	pool.SetMaxIdleConns(3)
	pool.SetMaxOpenConns(3)

	ctx, stop := context.WithCancel(context.Background())
	defer stop()

	appSignal := make(chan os.Signal, 3)
	signal.Notify(appSignal, os.Interrupt)

	go func() {
		<-appSignal
		stop()
	}()

	Ping(ctx)

	Query(ctx, *id)
}

// Ping数据库,以验证用户提供的DSN是否有效,服务器是否可以访问。如果Ping失败,则以错误退出程序。
func Ping(ctx context.Context) {
	ctx, cancel := context.WithTimeout(ctx, 1*time.Second)
	defer cancel()

	if err := pool.PingContext(ctx); err != nil {
		log.Fatalf("unable to connect to database: %v", err)
	}
}

// 在数据库中查询所要求的信息并打印出结果。
// 如果查询失败,则以错误退出程序。
func Query(ctx context.Context, id int64) {
	ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
	defer cancel()

	var name string
	err := pool.QueryRowContext(ctx, "select p.name from people as p where p.id = :id;", sql.Named("id", id)).Scan(&name)
	if err != nil {
		log.Fatal("unable to execute search query", err)
	}
	log.Println("name=", name)
}

Example (OpenDBService)

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
package main

import (
	"context"
	"database/sql"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"time"
)

func main() {
	// 打开驱动程序通常不会尝试连接数据库。这将不是连接错误,而是DSN解析错误或其他初始化错误。
	db, err := sql.Open("driver-name", "database=test1")
	if err != nil {
		// 打开驱动程序通常不会尝试连接数据库。
        这不会是连接错误,而是DSN解析错误或其他初始化错误。
		log.Fatal(err)
	}
	db.SetConnMaxLifetime(0)
	db.SetMaxIdleConns(50)
	db.SetMaxOpenConns(50)

	s := &Service{db: db}

	http.ListenAndServe(":8080", s)
}

type Service struct {
	db *sql.DB
}

func (s *Service) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	db := s.db
	switch r.URL.Path {
	default:
		http.Error(w, "not found", http.StatusNotFound)
		return
	case "/healthz":
		ctx, cancel := context.WithTimeout(r.Context(), 1*time.Second)
		defer cancel()

		err := s.db.PingContext(ctx)
		if err != nil {
			http.Error(w, fmt.Sprintf("db down: %v", err), http.StatusFailedDependency)
			return
		}
		w.WriteHeader(http.StatusOK)
		return
	case "/quick-action":
		// 这是一个短查询语句。使用请求上下文作为上下文超时的基础。
		ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second)
		defer cancel()

		id := 5
		org := 10
		var name string
		err := db.QueryRowContext(ctx, `
select
	p.name
from
	people as p
	join organization as o on p.organization = o.id
where
	p.id = :id
	and o.id = :org
;`,
			sql.Named("id", id),
			sql.Named("org", org),
		).Scan(&name)
		if err != nil {
			if err == sql.ErrNoRows {
				http.Error(w, "not found", http.StatusNotFound)
				return
			}
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		io.WriteString(w, name)
		return
	case "/long-action":
		// 这是一个长查询语句。使用请求上下文作为上下文超时的基础,
        // 但给它一些时间来完成。如果客户端在查询完成之前取消了操作,
        // 则该查询也将被取消。
		ctx, cancel := context.WithTimeout(r.Context(), 60*time.Second)
		defer cancel()

		var names []string
		rows, err := db.QueryContext(ctx, "select p.name from people as p where p.active = true;")
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		for rows.Next() {
			var name string
			err = rows.Scan(&name)
			if err != nil {
				break
			}
			names = append(names, name)
		}
		// 检查行"Close"时是否有错误。
        // 如果在单个批处理中执行了多个语句并且写入了行,那么这可能更重要。
		if closeErr := rows.Close(); closeErr != nil {
			http.Error(w, closeErr.Error(), http.StatusInternalServerError)
			return
		}

		// 检查行扫描错误。
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		// 检查行迭代过程中是否有错误。
		if err = rows.Err(); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		json.NewEncoder(w).Encode(names)
		return
	case "/async-action":
		// 这个操作有副作用,我们希望即使客户端在HTTP请求过程中部分取消了,
        // 它也能够保留。为此,我们不使用http请求上下文作为超时的基础。
		ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
		defer cancel()

		var orderRef = "ABC123"
		tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})
		_, err = tx.ExecContext(ctx, "stored_proc_name", orderRef)

		if err != nil {
			tx.Rollback()
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		err = tx.Commit()
		if err != nil {
			http.Error(w, "action in unknown state, check state before attempting again", http.StatusInternalServerError)
			return
		}
		w.WriteHeader(http.StatusOK)
		return
	}
}

常量

This section is empty.

变量

View Source

1
var ErrConnDone = errors.New("sql: connection is already closed")

​ ErrConnDone 被任何在已经返回到连接池的连接上执行的操作返回。

View Source

1
var ErrNoRows = errors.New("sql: no rows in result set")

​ ErrNoRows 在 Scan 时由 QueryRow 不返回行时返回。在这种情况下,QueryRow 返回一个占位符 *Row 值,直到扫描时才会出现此错误。

View Source

1
var ErrTxDone = errors.New("sql: transaction has already been committed or rolled back")

​ ErrTxDone 被任何在已经提交或回滚的事务上执行的操作返回。

函数

func Drivers <- go1.4

1
func Drivers() []string

​ Drivers函数返回已注册驱动程序名称的排序列表。

func Register

1
func Register(name string, driver driver.Driver)

​ Register函数使用提供的名称使数据库驱动程序可用。如果使用相同的名称两次调用Register或者驱动程序为nil,则会引发panic。

类型

type ColumnType <- go1.8

1
2
3
4
type ColumnType struct {
	// contains filtered or unexported fields
	// 包含已过滤或未导出的字段
}

​ ColumnType结构体包含列的名称和类型。

(*ColumnType) DatabaseTypeName <- go1.8

1
func (ci *ColumnType) DatabaseTypeName() string

​ DatabaseTypeName方法返回列类型的数据库系统名称。如果返回空字符串,则不支持驱动程序类型名称。请查阅您的驱动程序文档以获取驱动程序数据类型列表。不包括长度说明符。常见类型名称包括"VARCHAR",“TEXT”,“NVARCHAR”,“DECIMAL”,“BOOL”,“INT"和"BIGINT”。

(*ColumnType) DecimalSize <- go1.8

1
func (ci *ColumnType) DecimalSize() (precision, scale int64, ok bool)

​ DecimalSize方法返回十进制类型的比例和精度。如果不适用或不受支持,则为假。

(*ColumnType) Length <- go1.8

1
func (ci *ColumnType) Length() (length int64, ok bool)

​ Length方法返回变量长度列类型(如文本和二进制字段类型)的列类型长度。如果类型长度不受限制,则值将是math.MaxInt64(任何数据库限制仍将适用)。如果列类型不是可变长度,例如int,或者驱动程序不支持,则为false。

(*ColumnType) Name <- go1.8

1
func (ci *ColumnType) Name() string

​ Name方法返回列的名称或别名。

(*ColumnType) Nullable <- go1.8

1
func (ci *ColumnType) Nullable() (nullable, ok bool)

​ Nullable方法报告列是否可以为null。如果驱动程序不支持此属性,则ok将为false。

(*ColumnType) ScanType <- go1.8

1
func (ci *ColumnType) ScanType() reflect.Type

​ ScanType方法返回适合使用Rows.Scan进行扫描的Go类型。如果驱动程序不支持此属性,则ScanType将返回空接口的类型。

type Conn <- go1.9

1
2
3
4
type Conn struct {
	// contains filtered or unexported fields
	// 包含已过滤或未导出的字段
}

​ Conn结构体表示一个单独的数据库连接,而不是数据库连接池。除非有特定需要一个连续的单个数据库连接,否则请优先使用 DB 来运行查询。

​ 在调用 Close方法以将连接返回到数据库池之前,Conn 必须调用 Close方法,可能与正在运行的查询同时进行。

​ 调用 Close方法后,连接上的所有操作都将失败,并返回 ErrConnDone。

(*Conn) BeginTx <- go1.9

1
func (c *Conn) BeginTx(ctx context.Context, opts *TxOptions) (*Tx, error)

​ BeginTx方法开始一个事务。

​ 提供的上下文会一直使用到事务提交或回滚。如果上下文被取消,sql 包将回滚事务。如果传递给 BeginTx 的上下文被取消,Tx.Commit 将返回一个错误。

​ 提供的 TxOptions 是可选的,如果应使用默认值,则可以为 nil。如果使用了非默认的隔离级别,并且该驱动程序不支持,将返回一个错误。

(*Conn) Close <- go1.9

1
func (c *Conn) Close() error

​ Close方法将连接返回到连接池。Close方法后的所有操作都将返回 ErrConnDone。Close 方法可以与其他操作并发调用,它将阻塞,直到所有其他操作完成。在调用 Close 前,先取消任何使用的上下文,然后直接调用它可能会很有用。

(*Conn) ExecContext <- go1.9

1
func (c *Conn) ExecContext(ctx context.Context, query string, args ...any) (Result, error)

​ ExecContext方法执行一条查询,而不返回任何行。args 用于查询中的任何占位符参数。

ExecContext Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package main

import (
	"context"
	"database/sql"
	"log"
)

var (
	ctx context.Context
	db  *sql.DB
)

func main() {
	// A *DB is a pool of connections. Call Conn to reserve a connection for
	// exclusive use.
	conn, err := db.Conn(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close() // Return the connection to the pool.
	id := 41
	result, err := conn.ExecContext(ctx, `UPDATE balances SET balance = balance + 10 WHERE user_id = ?;`, id)
	if err != nil {
		log.Fatal(err)
	}
	rows, err := result.RowsAffected()
	if err != nil {
		log.Fatal(err)
	}
	if rows != 1 {
		log.Fatalf("expected single row affected, got %d rows affected", rows)
	}
}

(*Conn) PingContext <- go1.9

1
func (c *Conn) PingContext(ctx context.Context) error

​ PingContext方法验证与数据库的连接是否仍然存活。

(*Conn) PrepareContext <- go1.9

1
func (c *Conn) PrepareContext(ctx context.Context, query string) (*Stmt, error)

​ PrepareContext方法为以后的查询或执行创建一个准备好的语句。可以从返回的语句中并发运行多个查询或执行。调用者在不再需要语句时必须调用语句的 Close 方法。

​ 提供的上下文用于准备语句,而不是执行语句的上下文。

(*Conn) QueryContext <- go1.9

1
func (c *Conn) QueryContext(ctx context.Context, query string, args ...any) (*Rows, error)

​ QueryContext方法执行一个返回行的查询,通常是SELECT。args参数用于查询中的任何占位符参数。

(*Conn) QueryRowContext <- go1.9

1
func (c *Conn) QueryRowContext(ctx context.Context, query string, args ...any) *Row

​ QueryRowContext方法执行一个预期返回最多一行的查询。QueryRowContext总是返回一个非nil值。错误会被推迟到调用Row的Scan方法时返回。如果查询没有选择任何行,则* Row的Scan将返回ErrNoRows。否则,*Row的Scan扫描第一个选择的行并丢弃其余的行。

(*Conn) Raw <- go1.13

1
func (c *Conn) Raw(f func(driverConn any) error) (err error)

​ Raw方法执行f,暴露底层驱动程序连接。driverConn不能在f之外使用。

​ 一旦f返回且err不是driver.ErrBadConn,Conn将继续可用,直到调用Conn.Close为止。

type DB

1
2
3
type DB struct {
	// contains filtered or unexported fields
}

​ DB结构体是表示零个或多个底层连接池的数据库句柄。它可以被多个goroutine并发使用。

​ sql包会自动创建和释放连接;它还维护一个空闲连接的自由池。如果数据库有每个连接状态的概念,则可以在事务(Tx)或连接(Conn)中可靠地观察到此状态。一旦调用DB.Begin,返回的Tx将绑定到单个连接。一旦在事务上调用Commit或Rollback,该事务的连接就会返回到DB的空闲连接池中。池的大小可以使用SetMaxIdleConns进行控制。

func Open

1
func Open(driverName, dataSourceName string) (*DB, error)

​ Open函数通过其数据库驱动程序名称和驱动程序特定的数据源名称打开一个数据库,通常至少包含数据库名称和连接信息。

​ 大多数用户将通过返回*DB的特定于驱动程序的连接助手函数打开数据库。Go标准库中不包含任何数据库驱动程序。请参阅https://golang.org/s/sqldrivers以获取第三方驱动程序的列表。

​ Open函数可能只验证其参数而不创建到数据库的连接。要验证数据源名称是否有效,请调用Ping。

​ 返回的DB可安全地由多个goroutine并发使用,并维护其自己的空闲连接池。因此,应该只调用一次Open函数。很少需要关闭DB。

func OpenDB <- go1.10

1
func OpenDB(c driver.Connector) *DB

​ OpenDB函数使用Connector打开数据库,允许驱动程序绕过基于字符串的数据源名称。

​ 大多数用户将通过特定于驱动程序的连接助手函数打开数据库,该函数返回*DB。Go标准库中不包含任何数据库驱动程序。有关第三方驱动程序的列表,请参见https://golang.org/s/sqldrivers。

​ OpenDB函数可能只是验证其参数而没有创建到数据库的连接。要验证数据源名称是否有效,请调用Ping。

​ 返回的DB安全地支持多个goroutine的并发使用,并维护其自己的空闲连接池。因此,OpenDB函数应该只调用一次。很少需要关闭DB。

(*DB) Begin

1
func (db *DB) Begin() (*Tx, error)

​ Begin方法开始一个事务。默认的隔离级别取决于驱动程序。

​ Begin方法在内部使用context.Background;要指定上下文,请使用BeginTx方法。

(*DB) BeginTx <- go1.8

1
func (db *DB) BeginTx(ctx context.Context, opts *TxOptions) (*Tx, error)

​ BeginTx方法开始一个事务。

​ 提供的上下文用于直到事务提交或回滚。如果上下文被取消,则sql包将回滚事务。如果提供给BeginTx方法的上下文被取消,Tx.Commit将返回错误。

​ 提供的TxOptions是可选的,如果应使用默认值,则可以为nil。如果使用驱动程序不支持的非默认隔离级别,则会返回错误。

BeginTx Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package main

import (
	"context"
	"database/sql"
	"log"
)

var (
	ctx context.Context
	db  *sql.DB
)

func main() {
	tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})
	if err != nil {
		log.Fatal(err)
	}
	id := 37
	_, execErr := tx.Exec(`UPDATE users SET status = ? WHERE id = ?`, "paid", id)
	if execErr != nil {
		_ = tx.Rollback()
		log.Fatal(execErr)
	}
	if err := tx.Commit(); err != nil {
		log.Fatal(err)
	}
}

(*DB) Close

1
func (db *DB) Close() error

​ Close方法关闭数据库并防止启动新查询。然后,Close方法等待在服务器上已经开始处理的所有查询完成。

​ 很少需要关闭DB,因为DB句柄应该是长期存在的并在许多goroutine之间共享。

(*DB) Conn <- go1.9

1
func (db *DB) Conn(ctx context.Context) (*Conn, error)

​ Conn方法通过打开一个新连接或从连接池中返回一个现有连接来返回单个连接。 Conn 将阻塞直到返回连接或取消 ctx。在同一 Conn 上运行的查询将在同一个数据库会话中运行。

​ 每个 Conn方法必须通过调用 Conn.Close 返回到数据库池中。

(*DB) Driver

1
func (db *DB) Driver() driver.Driver

​ Driver方法返回数据库的底层驱动程序。

(*DB) Exec

1
func (db *DB) Exec(query string, args ...any) (Result, error)

​ Exec方法执行一个查询,而不返回任何行。 args 是查询中任何占位符参数的参数。

​ Exec方法内部使用 context.Background。要指定上下文,请使用 ExecContext方法。

(*DB) ExecContext <- go1.8

1
func (db *DB) ExecContext(ctx context.Context, query string, args ...any) (Result, error)

​ ExecContext方法执行一个查询,而不返回任何行。 args 是查询中任何占位符参数的参数。

ExecContext Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package main

import (
	"context"
	"database/sql"
	"log"
)

var (
	ctx context.Context
	db  *sql.DB
)

func main() {
	id := 47
	result, err := db.ExecContext(ctx, "UPDATE balances SET balance = balance + 10 WHERE user_id = ?", id)
	if err != nil {
		log.Fatal(err)
	}
	rows, err := result.RowsAffected()
	if err != nil {
		log.Fatal(err)
	}
	if rows != 1 {
		log.Fatalf("expected to affect 1 row, affected %d", rows)
	}
}

(*DB) Ping <- go1.1

1
func (db *DB) Ping() error

​ Ping方法验证与数据库的连接仍然存在,必要时建立连接。

​ Ping方法内部使用 context.Background。要指定上下文,请使用 PingContext方法。

(*DB) PingContext <- go1.8

1
func (db *DB) PingContext(ctx context.Context) error

​ PingContext方法验证与数据库的连接仍然存在,必要时建立连接。

PingContext Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package main

import (
	"context"
	"database/sql"
	"log"
	"time"
)

var (
	ctx context.Context
	db  *sql.DB
)

func main() {
	// Ping和PingContext可用于确定是否仍然可以与数据库服务器通信。
	//
	// 在命令行应用程序中使用Ping可以建立进一步查询是可能的;DSN是有效的。
	//
	// 在长时间运行的服务中,Ping可以是健康检查系统的一部分。
	ctx, cancel := context.WithTimeout(ctx, 1*time.Second)
	defer cancel()

	status := "up"
	if err := db.PingContext(ctx); err != nil {
		status = "down"
	}
	log.Println(status)
}

(*DB) Prepare

1
func (db *DB) Prepare(query string) (*Stmt, error)

​ Prepare方法创建一个准备好的语句,以便以后进行查询或执行操作。可以从返回的语句中并发运行多个查询或执行。调用者在语句不再需要时必须调用语句的 Close 方法。

​ Prepare方法内部使用 context.Background。要指定上下文,请使用 PrepareContext方法。

Prepare Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package main

import (
	"context"
	"database/sql"
	"log"
)

var db *sql.DB

func main() {
	projects := []struct {
		mascot  string
		release int
	}{
		{"tux", 1991},
		{"duke", 1996},
		{"gopher", 2009},
		{"moby dock", 2013},
	}

	stmt, err := db.Prepare("INSERT INTO projects(id, mascot, release, category) VALUES( ?, ?, ?, ? )")
	if err != nil {
		log.Fatal(err)
	}
	defer stmt.Close() // Prepared statements take up server resources and should be closed after use.

	for id, project := range projects {
		if _, err := stmt.Exec(id+1, project.mascot, project.release, "open source"); err != nil {
			log.Fatal(err)
		}
	}
}

(*DB) PrepareContext <- go1.8

1
func (db *DB) PrepareContext(ctx context.Context, query string) (*Stmt, error)

​ PrepareContext方法创建一个准备好的语句,以便以后进行查询或执行操作。可以从返回的语句中并发运行多个查询或执行。调用者在语句不再需要时必须调用语句的 Close 方法。

​ 提供的上下文用于语句的准备,而不是语句的执行。

(*DB) Query

1
func (db *DB) Query(query string, args ...any) (*Rows, error)

​ Query方法执行返回行的查询,通常是 SELECT。args 是查询中的任何占位符参数。

​ Query方法内部使用 context.Background。要指定上下文,请使用 QueryContext方法。

Query Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package main

import (
	"context"
	"database/sql"
	"log"
)

var db *sql.DB

func main() {
	age := 27
	q := `
create temp table uid (id bigint); -- Create temp table for queries.
insert into uid
select id from users where age < ?; -- Populate temp table.

-- First result set.
select
	users.id, name
from
	users
	join uid on users.id = uid.id
;

-- Second result set.
select 
	ur.user, ur.role
from
	user_roles as ur
	join uid on uid.id = ur.user
;
	`
	rows, err := db.Query(q, age)
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()

	for rows.Next() {
		var (
			id   int64
			name string
		)
		if err := rows.Scan(&id, &name); err != nil {
			log.Fatal(err)
		}
		log.Printf("id %d name is %s\n", id, name)
	}
	if !rows.NextResultSet() {
		log.Fatalf("expected more result sets: %v", rows.Err())
	}
	var roleMap = map[int64]string{
		1: "user",
		2: "admin",
		3: "gopher",
	}
	for rows.Next() {
		var (
			id   int64
			role int64
		)
		if err := rows.Scan(&id, &role); err != nil {
			log.Fatal(err)
		}
		log.Printf("id %d has role %s\n", id, roleMap[role])
	}
	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}
}

(*DB) QueryContext <- go1.8

1
func (db *DB) QueryContext(ctx context.Context, query string, args ...any) (*Rows, error)

​ QueryContext方法执行返回行的查询,通常是 SELECT。args 是查询中的任何占位符参数。

QueryContext Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package main

import (
	"context"
	"database/sql"
	"fmt"
	"log"
	"strings"
)

var (
	ctx context.Context
	db  *sql.DB
)

func main() {
	age := 27
	rows, err := db.QueryContext(ctx, "SELECT name FROM users WHERE age=?", age)
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()
	names := make([]string, 0)

	for rows.Next() {
		var name string
		if err := rows.Scan(&name); err != nil {
			// Check for a scan error.
			// Query rows will be closed with defer.
			log.Fatal(err)
		}
		names = append(names, name)
	}
	// If the database is being written to ensure to check for Close
	// errors that may be returned from the driver. The query may
	// encounter an auto-commit error and be forced to rollback changes.
	rerr := rows.Close()
	if rerr != nil {
		log.Fatal(rerr)
	}

	// Rows.Err will report the last error encountered by Rows.Scan.
	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%s are %d years old", strings.Join(names, ", "), age)
}

(*DB) QueryRow

1
func (db *DB) QueryRow(query string, args ...any) *Row

​ QueryRow方法执行一个预期返回最多一行的查询。QueryRow方法总是返回一个非空值。错误将被延迟直到调用 Row 的 Scan 方法。如果查询未选择任何行,则 *Row 的 Scan 将返回 ErrNoRows。否则,*Row 的 Scan 扫描第一行并丢弃其余行。

​ QueryRow方法内部使用 context.Background。要指定上下文,请使用 QueryRowContext方法。

(*DB) QueryRowContext <- go1.8

1
func (db *DB) QueryRowContext(ctx context.Context, query string, args ...any) *Row

​ QueryRowContext方法执行一个预期返回最多一行的查询。QueryRowContext 总是返回一个非空值。错误将被延迟直到调用 Row 的 Scan 方法。如果查询未选择任何行,则 *Row 的 Scan 将返回 ErrNoRows。否则,*Row 的 Scan 扫描第一行并丢弃其余行。

QueryRowContext Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package main

import (
	"context"
	"database/sql"
	"log"
	"time"
)

var (
	ctx context.Context
	db  *sql.DB
)

func main() {
	id := 123
	var username string
	var created time.Time
	err := db.QueryRowContext(ctx, "SELECT username, created_at FROM users WHERE id=?", id).Scan(&username, &created)
	switch {
	case err == sql.ErrNoRows:
		log.Printf("no user with id %d\n", id)
	case err != nil:
		log.Fatalf("query error: %v\n", err)
	default:
		log.Printf("username is %q, account created on %s\n", username, created)
	}
}

(*DB) SetConnMaxIdleTime <- go1.15

1
func (db *DB) SetConnMaxIdleTime(d time.Duration)

​ SetConnMaxIdleTime方法设置连接的最大空闲时间。

​ 过期的连接可能会在重新使用之前被懒惰地关闭。

​ 如果d <= 0,则连接不会因连接的空闲时间而关闭。

(*DB) SetConnMaxLifetime <- go1.6

1
func (db *DB) SetConnMaxLifetime(d time.Duration)

​ SetConnMaxLifetime方法设置连接可以被重用的最长时间。

​ 到期的连接可能会在重用之前被懒惰地关闭。

​ 如果d <= 0,则不会因连接的年龄而关闭连接。

(*DB) SetMaxIdleConns <- go1.1

1
func (db *DB) SetMaxIdleConns(n int)

​ SetMaxIdleConns方法设置空闲连接池中的最大连接数。

​ 如果MaxOpenConns大于0但小于新的MaxIdleConns,则新的MaxIdleConns将被减少以匹配MaxOpenConns限制。

​ 如果n <= 0,则不会保留空闲连接。

​ 默认的最大空闲连接数当前为2。这可能会在将来的版本中更改。

(*DB) SetMaxOpenConns <- go1.2

1
func (db *DB) SetMaxOpenConns(n int)

​ SetMaxOpenConns方法设置打开到数据库的最大连接数。

​ 如果MaxIdleConns大于0且新的MaxOpenConns小于MaxIdleConns,则MaxIdleConns将被减少以匹配新的MaxOpenConns限制。

​ 如果n <= 0,则没有打开连接的数量限制。默认值为0(无限制)。

(*DB) Stats <- go1.5

1
func (db *DB) Stats() DBStats

​ Stats方法返回数据库统计信息。

type DBStats <- go1.5

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
type DBStats struct {
	MaxOpenConnections int //打开到数据库的最大连接数。

	// 池状态
	OpenConnections int // 在使用和空闲中建立的连接数。
	InUse           int // 当前正在使用的连接数。
	Idle            int // 空闲连接数。

	// 计数器
	WaitCount         int64         // 等待新连接的总数。
	WaitDuration      time.Duration // 阻止等待新连接的总时间。
	MaxIdleClosed     int64 // 由于SetMaxIdleConns而关闭的连接总数。
	MaxIdleTimeClosed int64 // 由于SetConnMaxIdleTime而关闭的连接总数。
	MaxLifetimeClosed int64 // 由于SetConnMaxLifetime而关闭的连接总数。
}

​ DBStats包含数据库统计信息。

type IsolationLevel <- go1.8

1
type IsolationLevel int

​ IsolationLevel是在TxOptions中使用的事务隔离级别。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
const (
	LevelDefault IsolationLevel = iota
	LevelReadUncommitted
	LevelReadCommitted
	LevelWriteCommitted
	LevelRepeatableRead
	LevelSnapshot
	LevelSerializable
	LevelLinearizable
)

​ 各种隔离级别,驱动程序可以在BeginTx中支持。如果驱动程序不支持给定的隔离级别,则可能返回错误。

​ 参见https://en.wikipedia.org/wiki/Isolation_(database_systems)#Isolation_levels。

(IsolationLevel) String <- go1.11

1
func (i IsolationLevel) String() string

​ String 函数返回事务隔离级别的名称。

type NamedArg <- go1.8

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
type NamedArg struct {

	// Name 是参数占位符的名称。
	//
	// 如果为空,则使用参数列表中的序号。
	//
	// Name 必须省略任何符号前缀。	
	Name string

	// Value 是参数的值。
	// 它可以被赋予与查询参数相同的值类型。
	Value any
    // 包含已过滤或未导出的字段
}

​ NamedArg 是一个命名参数。NamedArg 值可以作为参数传递给 Query 或 Exec 并绑定到 SQL 语句中相应的命名参数。

​ 为了更简洁地创建 NamedArg 值,请参考 Named 函数。

func Named <- go1.8

1
func Named(name string, value any) NamedArg

​ Named 函数提供了一种更简洁的方式来创建 NamedArg 值。

Example usage:

使用示例:

1
2
3
4
5
6
7
8
db.ExecContext(ctx, `
    delete from Invoice
    where
        TimeCreated < @end
        and TimeCreated >= @start;`,
    sql.Named("start", startTime),
    sql.Named("end", endTime),
)

type NullBool

1
2
3
4
type NullBool struct {
	Bool  bool
	Valid bool // 如果Bool不是NULL,Valid为真。
}

​ NullBool结构体表示可能为空的 bool 值。NullBool 实现了 Scanner 接口,因此它可以用作扫描目标,类似于 NullString。

(*NullBool) Scan

1
func (n *NullBool) Scan(value any) error

​ Scan方法实现了 Scanner 接口。

(NullBool) Value

1
func (n NullBool) Value() (driver.Value, error)

​ Value方法实现了 driver Valuer 接口。

type NullByte <- go1.17

1
2
3
4
type NullByte struct {
	Byte  byte
	Valid bool // 如果 Byte 不为 NULL,则 Valid 为 true
}

​ NullByte结构体表示一个可能为空的 byte。NullByte 实现了 Scanner 接口,因此它可以像 NullString 一样用作扫描目标。

(*NullByte) Scan <- go1.17

1
func (n *NullByte) Scan(value any) error

​ Scan方法实现了 Scanner 接口。

(NullByte) Value <- go1.17

1
func (n NullByte) Value() (driver.Value, error)

​ Value方法实现了 driver Valuer 接口。

type NullFloat64

1
2
3
4
type NullFloat64 struct {
	Float64 float64
	Valid   bool // 如果 Float64 不为 NULL,则 Valid 为 true
}

​ NullFloat64结构体表示一个可能为空的 float64。NullFloat64 实现了 Scanner 接口,因此它可以像 NullString 一样用作扫描目标。

(*NullFloat64) Scan

1
func (n *NullFloat64) Scan(value any) error

​ Scan方法实现了 Scanner 接口。

(NullFloat64) Value

1
func (n NullFloat64) Value() (driver.Value, error)

​ Value方法实现了 driver Valuer 接口。

type NullInt16 <- go1.17

1
2
3
4
type NullInt16 struct {
	Int16 int16
	Valid bool // 如果Int16不是NULL,Valid为true
}

​ NullInt16结构体表示可能为null的int16。NullInt16实现Scanner接口,因此它可以用作扫描目标,类似于NullString。

(*NullInt16) Scan <- go1.17

1
func (n *NullInt16) Scan(value any) error

​ Scan方法实现Scanner接口。

(NullInt16) Value <- go1.17

1
func (n NullInt16) Value() (driver.Value, error)

​ Value方法实现driver Valuer接口。

type NullInt32 <- go1.13

1
2
3
4
type NullInt32 struct {
	Int32 int32
	Valid bool //如果Int32不是NULL,Valid为true
}

​ NullInt32结构体表示可能为null的int32。NullInt32实现Scanner接口,因此它可以用作扫描目标,类似于NullString。

(*NullInt32) Scan <- go1.13

1
func (n *NullInt32) Scan(value any) error

​ Scan方法实现Scanner接口。

(NullInt32) Value <- go1.13

1
func (n NullInt32) Value() (driver.Value, error)

​ Value方法实现driver Valuer接口。

type NullInt64

1
2
3
4
type NullInt64 struct {
	Int64 int64
	Valid bool // 如果Int64不是NULL,Valid为true
}

​ NullInt64结构体表示可能为null的int64。NullInt64实现Scanner接口,因此它可以用作扫描目标,类似于NullString。

(*NullInt64) Scan

1
func (n *NullInt64) Scan(value any) error

​ Scan方法实现Scanner接口。

(NullInt64) Value

1
func (n NullInt64) Value() (driver.Value, error)

​ Value方法实现driver Valuer接口。

type NullString

1
2
3
4
type NullString struct {
	String string
	Valid  bool // 如果 String 不为 NULL,则 Valid 为 true
}

​ NullString结构体表示可能为 null 的字符串。NullString 实现了 Scanner 接口,因此可以用作扫描目标:

1
2
3
4
5
6
7
8
var s NullString
err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&s)
...
if s.Valid {
   // use s.String
} else {
   // NULL value
}

(*NullString) Scan

1
func (ns *NullString) Scan(value any) error

​ Scan方法实现了 Scanner 接口。

(NullString) Value

1
func (ns NullString) Value() (driver.Value, error)

​ Value方法实现了 driver Valuer 接口。

type NullTime <- go1.13

1
2
3
4
type NullTime struct {
	Time  time.Time
	Valid bool // 如果 Time 不为 NULL,则 Valid 为 true
}

​ NullTime结构体表示可能为 null 的 time.Time。NullTime 实现了 Scanner 接口,因此可以用作扫描目标,类似于 NullString。

(*NullTime) Scan <- go1.13

1
func (n *NullTime) Scan(value any) error

​ Scan方法实现了 Scanner 接口。

(NullTime) Value <- go1.13

1
func (n NullTime) Value() (driver.Value, error)

​ Value方法实现了 driver Valuer 接口。

type Out <- go1.9

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
type Out struct {

	// Dest is a pointer to the value that will be set to the result of the
	// stored procedure's OUTPUT parameter.
    // Dest是一个指向将被设置为存储过程OUTPUT参数结果的值的指针。
	Dest any

	// In is whether the parameter is an INOUT parameter. If so, the input value to the stored
	// procedure is the dereferenced value of Dest's pointer, which is then replaced with
	// the output value.
    // In是指该参数是否为INOUT参数。如果是的话,存储过程的输入值是Dest指针的解引用值,然后用输出值替换。
	In bool
	// contains filtered or unexported fields
    //包含过滤过的或未导出的字段
}

​ Out结构体可用于从存储过程中检索 OUTPUT 值参数。

​ 并非所有驱动程序和数据库都支持 OUTPUT 值参数。

使用示例:

1
2
var outArg string
_, err := db.ExecContext(ctx, "ProcName", sql.Named("Arg1", sql.Out{Dest: &outArg}))

type RawBytes

1
type RawBytes []byte

​ RawBytes 是一个字节切片,它持有数据库本身拥有的内存引用。将 RawBytes扫描后,该切片仅在下一次调用 Next方法、Scan方法或 Close方法之前有效。

type Result

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
type Result interface {
	// LastInsertId 返回数据库在响应命令时生成的整数。
	// 通常这将来自插入新行时的"自增"列。
    // 不是所有数据库都支持此功能,并且此类语句的语法各不相同。
	LastInsertId() (int64, error)

	// RowsAffected 返回受更新、插入或删除影响的行数。
    // 并非所有数据库或数据库驱动程序都支持此功能。
	RowsAffected() (int64, error)
}

​ Result 是对执行的 SQL 命令的摘要。

type Row

1
2
3
type Row struct {
	// 包含已过滤或未导出的字段
}

​ Row结构体是调用 QueryRow方法选择单行时的结果。

(*Row) Err <- go1.15

1
func (r *Row) Err() error

​ Err方法提供了一种方法,使封装的包在不调用 Scan方法的情况下检查查询错误。如果在运行查询时遇到错误,Err 返回错误(如果有)。如果此错误不是 nil,则还将从 Scan 返回此错误。

(*Row) Scan

1
func (r *Row) Scan(dest ...any) error

​ Scan方法将匹配的行中的列复制到 dest 指向的值中。有关详细信息,请参见 Rows.Scan 的文档。如果有多行与查询匹配,则 Scan方法使用第一行并且忽略其余的行。如果没有行与查询匹配,则 Scan方法返回 ErrNoRows。

type Rows

1
2
3
4
type Rows struct {
	// contains filtered or unexported fields
	// 包含已过滤或未导出的字段
}

​ Rowsjgt是查询的结果。它的游标在结果集的第一行之前。使用 Next方法来从一行移到另一行。

Rows Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package main

import (
	"context"
	"database/sql"
	"log"
	"strings"
)

var (
	ctx context.Context
	db  *sql.DB
)

func main() {
	age := 27
	rows, err := db.QueryContext(ctx, "SELECT name FROM users WHERE age=?", age)
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()

	names := make([]string, 0)
	for rows.Next() {
		var name string
		if err := rows.Scan(&name); err != nil {
			log.Fatal(err)
		}
		names = append(names, name)
	}
	// Check for errors from iterating over rows.
	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}
	log.Printf("%s are %d years old", strings.Join(names, ", "), age)
}

(*Rows) Close

1
func (rs *Rows) Close() error

​ Close方法方法关闭 Rows,防止进一步枚举。如果调用 Next 并且返回 false,并且没有其他结果集,则 Rows 将自动关闭,并且检查 Err 的结果就足够了。Close方法是幂等的,不会影响 Err 的结果。

(*Rows) ColumnTypes <- go1.8

1
func (rs *Rows) ColumnTypes() ([]*ColumnType, error)

​ ColumnTypes方法返回列信息,例如列类型、长度和可空性。某些信息可能不适用于某些驱动程序。

(*Rows) Columns

1
func (rs *Rows) Columns() ([]string, error)

​ Columns方法返回列名。如果行已关闭,则 Columns方法返回错误。

(*Rows) Err

1
func (rs *Rows) Err() error

​ Err方法返回迭代过程中遇到的错误(如果有)。Err方法可以在显式或隐式 Close 后调用。

(*Rows) Next

1
func (rs *Rows) Next() bool

​ Next方法准备下一个结果行以供 Scan 方法读取。它返回 true 表示成功,false 表示没有下一个结果行或准备它时发生错误。应该使用 Err 来区分这两种情况。

​ 每次调用 Scan方法,即使是第一次调用,也必须先调用 Next方法。

(*Rows) NextResultSet <- go1.8

1
func (rs *Rows) NextResultSet() bool

​ NextResultSet方法准备下一个结果集以供读取。它返回 true 表示还有其他结果集,或者 false 表示没有其他结果集,或者无法提前到其结果集。应该使用 Err 方法来区分这两种情况。

​ 在调用 NextResultSet方法后,应始终在扫描之前调用 Next 方法。如果还有其他结果集,则它们可能没有结果集中的行。

(*Rows) Scan

1
func (rs *Rows) Scan(dest ...any) error

​ Scan方法将当前行的列复制到 dest 指向的值中。dest 中的值数量必须与 Rows 中的列数相同。

​ Scan方法将从数据库中读取的列转换为 sql 包提供的以下常见 Go 类型和特殊类型:

*string
*[]byte
*int, *int8, *int16, *int32, *int64
*uint, *uint8, *uint16, *uint32, *uint64
*bool
*float32, *float64
*interface{}
*RawBytes
*Rows (cursor value)
any type implementing Scanner (see Scanner docs)

​ 实现 Scanner 接口的任何类型(请参见 Scanner 文档) 在最简单的情况下,如果源列的值类型是整数、布尔或字符串类型 T,而 dest 的类型是 *T,则 Scan 只需通过指针分配值。

​ Scan 还可以在字符串和数字类型之间进行转换,只要不会丢失信息即可。虽然 Scan 将从数值数据库列中读取的所有数字字符串化为 *string,但会检查是否存在数字类型的扫描溢出。例如,值为 300 的 float64 或值为 “300” 的字符串可以扫描到 uint16,但不能扫描到 uint8,尽管 float64(255) 或 “255” 可以扫描到 uint8。有一个例外,即某些 float64 数字扫描为字符串时可能会丢失信息。通常,将浮点列扫描到 *float64 中。

​ 如果 dest 参数的类型为 *[]byte,则 Scan 会在该参数中保存相应数据的副本。该副本由调用方拥有,可以进行修改并无限期保留。可以通过使用类型 *RawBytes 的参数来避免复制;请参阅 RawBytes 的文档以了解其使用限制。

​ 如果一个参数的类型是 *interface{},Scan 会复制由底层驱动程序提供的值,而不进行转换。从类型 []byte 到 *interface{} 扫描时,会复制切片并且调用方拥有结果。

​ 类型 time.Time 的源值可以扫描到类型 *time.Time、*interface{}、*string 或 *[]byte 的值中。转换为后两者时,使用 time.RFC3339Nano。

​ 布尔类型的源值可以扫描到类型 *bool、*interface{}、string、[]byte 或 *RawBytes 中。

​ 对于扫描到 *bool,源可以是 true、false、1、0 或可由 strconv.ParseBool 解析的字符串输入。

​ Scan 还可以将查询返回的游标(例如 “select cursor(select * from my_table) from dual”)转换为 *Rows 值,该值本身可以进行扫描。如果父选择查询关闭了任何游标 *Rows,则父选择查询将关闭它。

​ 如果实现 Scanner 接口的第一个参数返回错误,则该错误将包装在返回的错误中。

type Scanner

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
type Scanner interface {
	// Scan从数据库驱动程序中分配一个值。
	//
	// src值将是以下类型之一:
	//
	// int64
	// float64
	// bool
	// []byte
	// string
	// time.Time
	// nil - 对于NULL值
	//
	// 如果不能存储值而不丢失信息,则应返回错误。
	//
	// 诸如[]byte之类的引用类型仅在下一次调用Scan之前有效,不应保留。
	// 它们的底层内存由驱动程序拥有。
	// 如果需要保留,则在下一次调用Scan之前复制其值。
	Scan(src any) error
}

​ Scanner是由Scan使用的接口。

type Stmt

1
2
3
type Stmt struct {
	// 包含已过滤或未导出的字段
}

​ Stmt结构体是一个预处理语句。Stmt对于多个goroutine并发使用是安全的。

​ 如果在Tx或Conn上准备了Stmt,则将永远绑定到单个底层连接。 如果Tx或Conn关闭,则Stmt将变得无法使用,所有操作都将返回错误。 如果在DB上准备了Stmt,则在DB的生命周期内将保持可用。当Stmt需要在新的底层连接上执行时, 它将自动在新连接上准备自己。

Stmt Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package main

import (
	"context"
	"database/sql"
	"log"
)

var (
	ctx context.Context
	db  *sql.DB
)

func main() {
	// In normal use, create one Stmt when your process starts.
	stmt, err := db.PrepareContext(ctx, "SELECT username FROM users WHERE id = ?")
	if err != nil {
		log.Fatal(err)
	}
	defer stmt.Close()

	// Then reuse it each time you need to issue the query.
	id := 43
	var username string
	err = stmt.QueryRowContext(ctx, id).Scan(&username)
	switch {
	case err == sql.ErrNoRows:
		log.Fatalf("no user with id %d", id)
	case err != nil:
		log.Fatal(err)
	default:
		log.Printf("username is %s\n", username)
	}
}

(*Stmt) Close

1
func (s *Stmt) Close() error

​ Close方法关闭该语句。

(*Stmt) Exec

1
func (s *Stmt) Exec(args ...any) (Result, error)

​ Exec方法使用给定的参数执行预处理语句,并返回概括语句效果的Result。

​ Exec方法在内部使用context.Background。要指定上下文,请使用ExecContext方法。

(*Stmt) ExecContext <- go1.8

1
func (s *Stmt) ExecContext(ctx context.Context, args ...any) (Result, error)

​ ExecContext方法使用给定的参数执行预处理语句,并返回概括语句效果的Result。

(*Stmt) Query

1
func (s *Stmt) Query(args ...any) (*Rows, error)

​ Query方法使用给定的参数执行预处理查询语句,并将查询结果作为*Rows返回。

​ Query方法在内部使用context.Background。要指定上下文,请使用QueryContext方法。

(*Stmt) QueryContext <- go1.8

1
func (s *Stmt) QueryContext(ctx context.Context, args ...any) (*Rows, error)

​ QueryContext方法使用给定的参数执行预处理查询语句,并将查询结果作为*Rows返回。

(*Stmt) QueryRow

1
func (s *Stmt) QueryRow(args ...any) *Row

​ QueryRow方法使用给定的参数执行预处理的查询语句。如果在执行语句期间出现错误,则通过对返回的*Row调用Scan返回该错误,该*Row始终非零。如果查询未选择任何行,则*Row的Scan将返回ErrNoRows。否则,*Row的Scan将扫描第一个选定的行并丢弃其余行。

使用示例:

1
2
var name string
err := nameByUseridStmt.QueryRow(id).Scan(&name)

​ QueryRow方法在内部使用context.Background;要指定上下文,请使用QueryRowContext方法。

(*Stmt) QueryRowContext <- go1.8

1
func (s *Stmt) QueryRowContext(ctx context.Context, args ...any) *Row

​ QueryRowContext方法使用给定的参数执行预处理的查询语句。如果在执行语句期间出现错误,则通过对返回的*Row调用Scan返回该错误,该*Row始终非零。如果查询未选择任何行,则*Row的Scan将返回ErrNoRows。否则,*Row的Scan将扫描第一个选定的行并丢弃其余行。

QueryRowContext Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package main

import (
	"context"
	"database/sql"
	"log"
)

var (
	ctx context.Context
	db  *sql.DB
)

func main() {
	// In normal use, create one Stmt when your process starts.
	stmt, err := db.PrepareContext(ctx, "SELECT username FROM users WHERE id = ?")
	if err != nil {
		log.Fatal(err)
	}
	defer stmt.Close()

	// Then reuse it each time you need to issue the query.
	id := 43
	var username string
	err = stmt.QueryRowContext(ctx, id).Scan(&username)
	switch {
	case err == sql.ErrNoRows:
		log.Fatalf("no user with id %d", id)
	case err != nil:
		log.Fatal(err)
	default:
		log.Printf("username is %s\n", username)
	}
}

type Tx

1
2
3
4
type Tx struct {
	// contains filtered or unexported fields
	// 包含已过滤或未导出的字段
}

​ Tx结构体是数据库事务中的一个过程。

​ 事务必须以Commit方法或Rollback方法的调用结束。

​ 在调用Commit方法或Rollback方法之后,所有事务上的操作都会失败并返回ErrTxDone。

​ 通过调用事务的Prepare方法或Stmt方法方法准备的语句将在调用Commit方法或Rollback方法时关闭。

(*Tx) Commit

1
func (tx *Tx) Commit() error

​ Commit方法提交事务。

(*Tx) Exec

1
func (tx *Tx) Exec(query string, args ...any) (Result, error)

​ Exec方法执行不返回行的查询。例如:INSERT和UPDATE。

​ Exec方法在内部使用context.Background;要指定上下文,请使用ExecContext方法。

(*Tx) ExecContext <- go1.8

1
func (tx *Tx) ExecContext(ctx context.Context, query string, args ...any) (Result, error)

​ ExecContext方法执行不返回行的查询。例如:INSERT和UPDATE。

ExecContext Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package main

import (
	"context"
	"database/sql"
	"log"
)

var (
	ctx context.Context
	db  *sql.DB
)

func main() {
	tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})
	if err != nil {
		log.Fatal(err)
	}
	id := 37
	_, execErr := tx.ExecContext(ctx, "UPDATE users SET status = ? WHERE id = ?", "paid", id)
	if execErr != nil {
		if rollbackErr := tx.Rollback(); rollbackErr != nil {
			log.Fatalf("update failed: %v, unable to rollback: %v\n", execErr, rollbackErr)
		}
		log.Fatalf("update failed: %v", execErr)
	}
	if err := tx.Commit(); err != nil {
		log.Fatal(err)
	}
}

(*Tx) Prepare

1
func (tx *Tx) Prepare(query string) (*Stmt, error)

​ Prepare方法创建一个准备好的语句以在事务中使用。

​ 返回的语句在事务中运行,并将在事务提交或回滚时关闭。

​ 要在此事务上使用现有的准备好的语句,请参见Tx.Stmt。

​ Prepare方法在内部使用context.Background; 要指定上下文,请使用PrepareContext。

Prepare Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package main

import (
	"context"
	"database/sql"
	"log"
)

var db *sql.DB

func main() {
	projects := []struct {
		mascot  string
		release int
	}{
		{"tux", 1991},
		{"duke", 1996},
		{"gopher", 2009},
		{"moby dock", 2013},
	}

	tx, err := db.Begin()
	if err != nil {
		log.Fatal(err)
	}
	defer tx.Rollback() // The rollback will be ignored if the tx has been committed later in the function.

	stmt, err := tx.Prepare("INSERT INTO projects(id, mascot, release, category) VALUES( ?, ?, ?, ? )")
	if err != nil {
		log.Fatal(err)
	}
	defer stmt.Close() // Prepared statements take up server resources and should be closed after use.

	for id, project := range projects {
		if _, err := stmt.Exec(id+1, project.mascot, project.release, "open source"); err != nil {
			log.Fatal(err)
		}
	}
	if err := tx.Commit(); err != nil {
		log.Fatal(err)
	}
}

(*Tx) PrepareContext <- go1.8

1
func (tx *Tx) PrepareContext(ctx context.Context, query string) (*Stmt, error)

​ PrepareContext方法创建一个准备好的语句以在事务中使用。

​ 返回的语句在事务中运行,并将在事务提交或回滚时关闭。

​ 要在此事务上使用现有的准备好的语句,请参见Tx.Stmt。

​ 提供的上下文将用于准备上下文,而不是用于执行返回的语句。返回的语句将在事务上下文中运行。

(*Tx) Query

1
func (tx *Tx) Query(query string, args ...any) (*Rows, error)

​ Query方法执行返回行的查询,通常是 SELECT。

​ Query方法在内部使用context.Background;要指定上下文,请使用QueryContext方法。

(*Tx) QueryContext <- go1.8

1
func (tx *Tx) QueryContext(ctx context.Context, query string, args ...any) (*Rows, error)

​ QueryContext方法执行返回行的查询,通常是 SELECT。

(*Tx) QueryRow

1
func (tx *Tx) QueryRow(query string, args ...any) *Row

​ QueryRow方法执行预期最多返回一行的查询。QueryRow方法总是返回一个非空值。错误被延迟到调用 Row 的 Scan 方法时才会返回。如果查询未选择行,则 *Row 的 Scan 将返回 ErrNoRows。否则,*Row 的 Scan 扫描第一个选择的行并丢弃其余的行。

​ QueryRow方法在内部使用context.Background;要指定上下文,请使用QueryRowContext。

(*Tx) QueryRowContext <- go1.8

1
func (tx *Tx) QueryRowContext(ctx context.Context, query string, args ...any) *Row

​ QueryRowContext方法执行预期最多返回一行的查询。QueryRowContext方法总是返回一个非空值。错误被延迟到调用 Row 的 Scan 方法时才会返回。如果查询未选择行,则 *Row 的 Scan 将返回 ErrNoRows。否则,*Row 的 Scan 扫描第一个选择的行并丢弃其余的行。

(*Tx) Rollback

1
func (tx *Tx) Rollback() error

​ Rollback方法中止事务。

Rollback Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package main

import (
	"context"
	"database/sql"
	"log"
)

var (
	ctx context.Context
	db  *sql.DB
)

func main() {
	tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})
	if err != nil {
		log.Fatal(err)
	}
	id := 53
	_, err = tx.ExecContext(ctx, "UPDATE drivers SET status = ? WHERE id = ?;", "assigned", id)
	if err != nil {
		if rollbackErr := tx.Rollback(); rollbackErr != nil {
			log.Fatalf("update drivers: unable to rollback: %v", rollbackErr)
		}
		log.Fatal(err)
	}
	_, err = tx.ExecContext(ctx, "UPDATE pickups SET driver_id = $1;", id)
	if err != nil {
		if rollbackErr := tx.Rollback(); rollbackErr != nil {
			log.Fatalf("update failed: %v, unable to back: %v", err, rollbackErr)
		}
		log.Fatal(err)
	}
	if err := tx.Commit(); err != nil {
		log.Fatal(err)
	}
}

(*Tx) Stmt

1
func (tx *Tx) Stmt(stmt *Stmt) *Stmt

​ Stmt方法从现有语句返回一个事务特定的准备好的语句。

示例:

1
2
3
4
5
updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?")
...
tx, err := db.Begin()
...
res, err := tx.Stmt(updateMoney).Exec(123.45, 98293203)

​ 返回的语句在事务中运行,并在事务提交或回滚后关闭。

​ Stmt在内部使用context.Background;要指定上下文,请使用StmtContext。

(*Tx) StmtContext <- go1.8

1
func (tx *Tx) StmtContext(ctx context.Context, stmt *Stmt) *Stmt

​ StmtContext方法从现有语句返回一个事务特定的准备语句。

Example:

1
2
3
4
5
updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?")
...
tx, err := db.Begin()
...
res, err := tx.StmtContext(ctx, updateMoney).Exec(123.45, 98293203)

​ 提供的上下文用于准备语句,而不是执行语句。

​ 返回的语句在事务中运行,并在事务提交或回滚后关闭。

type TxOptions <- go1.8

1
2
3
4
5
6
type TxOptions struct {
	// Isolation是事务隔离级别。
	// 如果为零,则使用驱动程序或数据库的默认级别。
	Isolation IsolationLevel
	ReadOnly  bool
}

​ TxOptions保存在DB.BeginTx中使用的事务选项。

5.2 - sql/driver

driver

https://pkg.go.dev/database/sql/driver@go1.20.1

​ driver包定义了数据库驱动需要实现的接口,供sql包使用。

​ 大多数代码应该使用 sql 包。

​ 驱动程序接口随着时间的推移而发展。驱动程序应该实现 Connector 和 DriverContext 接口。Connector.Connect 和 Driver.Open 方法不应返回 ErrBadConn。如果连接已经处于无效状态(例如已关闭),则 ErrBadConn 只能从 Validator、SessionResetter 或查询方法中返回。

​ 所有 Conn 实现都应该实现以下接口:Pinger、SessionResetter 和 Validator。

​ 如果支持命名参数或上下文,则驱动程序的 Conn 应实现:ExecerContext、QueryerContext、ConnPrepareContext 和 ConnBeginTx。

​ 为支持自定义数据类型,实现 NamedValueChecker。NamedValueChecker 还允许查询通过返回 ErrRemoveArgument 接受每个查询选项作为参数。

​ 如果支持多个结果集,则 Rows 应实现 RowsNextResultSet。如果驱动程序知道返回结果中存在的类型,它应该实现以下接口:RowsColumnTypeScanType、RowsColumnTypeDatabaseTypeName、RowsColumnTypeLength、RowsColumnTypeNullable 和 RowsColumnTypePrecisionScale。给定行值也可以返回 Rows 类型,它可能表示数据库游标值。

​ 在将连接归还给连接池之前,如果实现了 IsValid,则会调用 IsValid。在将连接用于另一个查询之前,如果实现了 ResetSession,则会调用 ResetSession。如果连接从未返回给连接池,而是立即重用,则在重用之前调用 ResetSession,但不调用 IsValid。

常量

This section is empty.

变量

View Source

1
var Bool boolType

​ Bool是ValueConverter,用于将输入值转换为布尔值。

转换规则如下:

  • 布尔值不变
  • 对于整数类型,1为真,0为假,其他整数为错误
  • 对于字符串和[]byte,与strconv.ParseBool相同的规则
  • 所有其他类型都是一个错误

View Source

1
var DefaultParameterConverter defaultConverter

​ DefaultParameterConverter是ValueConverter的默认实现,当Stmt未实现ColumnConverter时使用。

​ DefaultParameterConverter如果IsValue(arg)则直接返回其参数。否则,如果参数实现了Valuer,则使用其Value方法返回一个Value。作为后备,提供的参数的基础类型用于将其转换为Value:基础整数类型转换为int64,浮点数转换为float64,bool,string和[]byte转换为自身。如果参数是nil指针,则ConvertValue返回nil Value。如果参数是非nil指针,则对其进行取消引用,并递归调用ConvertValue。其他类型是一个错误。

View Source

1
var ErrBadConn = errors.New("driver: bad connection")

​ 如果驱动程序处于错误状态(例如服务器早期关闭连接),则驱动程序应返回ErrBadConn,以向sql包发信号。sql包应该在新连接上重试。

​ 为了防止重复操作,如果数据库服务器可能执行操作,则不应返回ErrBadConn。即使服务器发送错误,您也不应返回ErrBadConn。

​ 使用errors.Is检查错误。一个错误可能包装ErrBadConn或实现Is(error) bool方法。

View Source

1
var ErrRemoveArgument = errors.New("driver: remove argument from query")

​ NamedValueChecker可能会返回ErrRemoveArgument,以指示sql包不将参数传递给驱动程序查询接口。在接受特定于查询的选项或不是SQL查询参数的结构时返回。

View Source

1
var ErrSkip = errors.New("driver: skip fast-path; continue as if unimplemented")

​ 某些可选接口的方法可能返回ErrSkip,以表示在运行时快速路径不可用,sql包应继续,就像未实现可选接口一样。仅在明确文档中记录了ErrSkip。

View Source

1
var Int32 int32Type

​ Int32是ValueConverter,用于将输入值转换为int64,并考虑int32值的限制。

View Source

1
var ResultNoRows noRows

​ ResultNoRows是预定义结果,驱动程序在DDL命令(如CREATE TABLE)成功时返回。它对于LastInsertId和RowsAffected都返回错误。

View Source

1
var String stringType

​ String是ValueConverter,用于将其输入转换为字符串。如果该值已经是字符串或[]byte,则不变。如果值是其他类型,则使用fmt.Sprintf("%v",v)进行字符串转换。

函数

func IsScanValue

1
func IsScanValue(v any) bool

​ IsScanValue函数等价于 IsValue。它存在是为了兼容性。

func IsValue

1
func IsValue(v any) bool

​ IsValue函数报告v是否为有效的 Value 参数类型。

类型

type Conn

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
type Conn interface {
	// Prepare 返回一个准备好的语句,与此连接绑定。
	Prepare(query string) (Stmt, error)

	// Close 使任何当前的准备语句和事务无效,标记此连接不再使用。
	//
	// 因为sql包维护一个空闲连接池,并且仅在空闲连接过多时调用Close,
    // 所以驱动程序不需要执行自己的连接缓存。
	//
	// 驱动程序必须确保Close调用所做的所有网络调用不会无限期地阻塞(例如,应用超时)。
	Close() error

    // Begin 启动并返回一个新的事务。
    //
    // 已弃用:驱动程序应该实现 ConnBeginTx 代替(或同时实现)。
	Begin() (Tx, error)
}

​ Conn 是到数据库的连接。它不会被多个goroutine同时使用。

​ Conn 被认为是有状态的。

type ConnBeginTx <- go1.8

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
type ConnBeginTx interface {
    // BeginTx 启动并返回一个新的事务。
    // 如果用户取消了上下文,sql包将在丢弃和关闭连接之前调用Tx.Rollback。
    //
    // 这必须检查opts.Isolation以确定是否有设置隔离级别。如果驱动程序不支持非默认级别,并且已设置一个级别,
    // 或者存在一个不支持的非默认隔离级别,则必须返回一个错误。
    //
    // 这还必须检查opts.ReadOnly以确定只读值是否为true,以设置只读事务属性(如果受支持),
    // 或者如果不支持,则返回错误。
	BeginTx(ctx context.Context, opts TxOptions) (Tx, error)
}

​ ConnBeginTx 使用上下文和 TxOptions 增强了 Conn 接口。

type ConnPrepareContext <- go1.8

1
2
3
4
5
type ConnPrepareContext interface {
    // PrepareContext 返回一个准备好的语句,与此连接绑定。
    // context 是用于准备语句的,它不能在语句本身中存储上下文。
	PrepareContext(ctx context.Context, query string) (Stmt, error)
}

​ ConnPrepareContext 通过上下文增强 Conn 接口。

type Connector <- go1.10

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
type Connector interface {
    // Connect 返回到数据库的连接。
    // Connect 可以返回缓存的连接(先前关闭的连接),但这样做是不必要的;
    // sql 包维护一个空闲连接池,以便有效地重复使用。
    //
    // 提供的 context.Context 仅用于拨号目的
    //(请参阅 net.DialContext),不应存储或用于其他目的。
    // 在拨号时仍应使用默认超时,因为连接池可以异步地调用 Connect 到任何查询。
    //
    // 返回的连接只由一个 goroutine 使用。
	Connect(context.Context) (Conn, error)

    // Driver 返回 Connector 的基础 Driver,
    // 主要是为了与 sql.DB 上的 Driver 方法保持兼容性。
	Driver() Driver
}

​ Connector 表示一个具有固定配置的驱动程序,并可以创建任意数量的等效 Conns 供多个 goroutine 使用。

​ 可以将 Connector 传递给 sql.OpenDB,以允许驱动程序实现其自己的 sql.DB 构造函数,或者由 DriverContext 的 OpenConnector 方法返回,以允许驱动程序访问上下文并避免重复解析驱动程序配置。

​ 如果 Connector 实现了 io.Closer,则 sql 包的 DB.Close 方法将调用 Close 并返回错误(如果有)。

type Driver

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
type Driver interface {
    // Open 返回到数据库的新连接。
    // 名称是驱动程序特定格式的字符串。
    //
    // Open 可以返回缓存的连接(先前关闭的连接),但这样做是不必要的;
    // sql 包维护一个空闲连接池,以便有效地重复使用。
    //
    // 返回的连接只由一个 goroutine 使用。
	Open(name string) (Conn, error)
}

​ Driver 是必须由数据库驱动程序实现的接口。

​ 数据库驱动程序可以实现 DriverContext,以便访问上下文并仅解析一次名称以获得连接池,而不是每个连接都解析一次。

type DriverContext <- go1.10

1
2
3
4
5
6
type DriverContext interface {
	// OpenConnector must parse the name in the same format that Driver.Open
	// parses the name parameter.
    // OpenConnector必须以Driver.Open解析名称参数的相同格式解析名称。
	OpenConnector(name string) (Connector, error)
}

​ 如果 Driver 实现了 DriverContext 接口,那么 sql.DB 将调用 OpenConnector 来获取 Connector,并调用该 Connector 的 Connect 方法来获取每个所需的连接,而不是为每个连接调用 Driver 的 Open 方法。这个两步的过程允许驱动程序只解析一次名称,并且提供对每个 Conn 的上下文访问。

type ExecerContext <- go1.8

1
2
3
type ExecerContext interface {
	ExecContext(ctx context.Context, query string, args []NamedValue) (Result, error)
}

​ ExecerContext 是一个可选接口,可以由 Conn 实现。

​ 如果 Conn 没有实现 ExecerContext,则 sql 包的 DB.Exec 将退回到 Execer;如果 Conn 也没有实现 Execer,则 DB.Exec 将首先准备查询,执行语句,然后关闭语句。

​ ExecContext 可能返回 ErrSkip。

​ ExecContext 必须遵守上下文超时,并在上下文取消时返回。

type IsolationLevel <- go1.8

1
type IsolationLevel int

​ IsolationLevel 是存储在 TxOptions 中的事务隔离级别。

​ 这个类型应该被认为与 sql.IsolationLevel 相同,以及其上定义的任何值。

type NamedValue <- go1.8

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
type NamedValue struct {
    // 如果 Name 不为空,应该用于参数标识符,而不是位置。
    //
    // Name 不会有符号前缀。
	Name string

	// 参数的序号位置,从一开始计数,并始终设置。
	Ordinal int	

    // Value是参数的值。
	Value Value
}

​ NamedValue 持有值的名称和值。

type NamedValueChecker <- go1.9

1
2
3
4
5
6
type NamedValueChecker interface {
    // CheckNamedValue 在将参数传递给驱动程序之前调用,
    // 并在任何 ColumnConverter 的位置调用。
    // CheckNamedValue 必须做类型验证和转换,以适合驱动程序。
	CheckNamedValue(*NamedValue) error
}

​ NamedValueChecker 可以由 Conn 或 Stmt 可选实现。它为驱动程序提供了更多的控制权,以处理超出默认的 Value 类型允许的 Go 和数据库类型。

​ sql包会按照以下顺序检查值检查器,并在找到第一个匹配项时停止:Stmt.NamedValueChecker、Conn.NamedValueChecker、Stmt.ColumnConverter和DefaultParameterConverter。

​ 如果CheckNamedValue返回ErrRemoveArgument,则NamedValue不会包含在最终查询参数中。这可用于向查询本身传递特殊选项。

​ 如果返回ErrSkip,则对于该参数将使用列转换器错误检查路径。驱动程序可能会在耗尽其自己的特殊情况后返回ErrSkip。

type NotNull

1
2
3
type NotNull struct {
	Converter ValueConverter
}

​ NotNull结构体是一种类型,通过禁止nil值但否则委托给另一个ValueConverter来实现ValueConverter。

(NotNull) ConvertValue

1
func (n NotNull) ConvertValue(v any) (Value, error)

type Null

1
2
3
type Null struct {
	Converter ValueConverter
}

​ Null结构体是一种类型,通过允许nil值但否则委托给另一个ValueConverter来实现ValueConverter。

(Null) ConvertValue

1
func (n Null) ConvertValue(v any) (Value, error)

type Pinger <- go1.8

1
2
3
type Pinger interface {
	Ping(ctx context.Context) error
}

​ Pinger是Conn可能实现的一个可选接口。

​ 如果Conn未实现Pinger,则sql包的DB.Ping和DB.PingContext将检查是否至少有一个Conn可用。

​ 如果Conn.Ping返回ErrBadConn,则DB.Ping和DB.PingContext将从池中删除Conn。

type QueryerContext <- go1.8

1
2
3
type QueryerContext interface {
	QueryContext(ctx context.Context, query string, args []NamedValue) (Rows, error)
}

​ QueryerContext是Conn可能实现的一个可选接口。

​ 如果Conn未实现QueryerContext,则sql包的DB.Query将回退到Queryer;如果Conn也未实现Queryer,则DB.Query将首先准备查询,执行语句,然后关闭语句。

​ QueryContext可能会返回ErrSkip。

​ QueryContext必须遵守上下文超时并在取消上下文时返回。

type Result

1
2
3
4
5
6
7
8
type Result interface {
	// LastInsertId 返回数据库生成的自增 ID,
	// 比如在插入一个带有主键的表时。
	LastInsertId() (int64, error)

	// RowsAffected 返回由查询所影响的行数。
	RowsAffected() (int64, error)
}

​ Result接口表示一个查询操作的结果。

type Rows

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
type Rows interface {
	// Columns 返回列的名称。
    // 结果集中列的数量从切片的长度中推断出来。如果特定列的名称未知,则该项应返回空字符串。
	Columns() []string

	// Close 关闭行迭代器。
	Close() error

    // Next 用来将下一行数据填充到提供的切片中。
    // 提供的切片将与 Columns() 的宽度相同。
    //
    // Next 应在没有更多行时返回 io.EOF。
    //
    // 在 Next 之外不应写入 dest。
    // 在关闭 Rows 时要小心,以免修改 dest 中保存的缓冲区。
	Next(dest []Value) error
}

​ Rows接口是一个已执行查询的结果集迭代器。

type RowsAffected

1
type RowsAffected int64

​ RowsAffected 表示执行 INSERT 或 UPDATE 操作所影响的行数,实现了 Result 接口。

(RowsAffected) LastInsertId

1
func (RowsAffected) LastInsertId() (int64, error)

(RowsAffected) RowsAffected

1
func (v RowsAffected) RowsAffected() (int64, error)

type RowsColumnTypeDatabaseTypeName <- go1.8

1
2
3
4
type RowsColumnTypeDatabaseTypeName interface {
	Rows
	ColumnTypeDatabaseTypeName(index int) string
}

​ RowsColumnTypeDatabaseTypeName接口可以被 Rows 实现。它应该返回数据库系统类型名称,但不包括长度信息。类型名称应大写。以下是各种类型的返回示例:“VARCHAR”、“NVARCHAR”、“VARCHAR2”、“CHAR”、“TEXT”、“DECIMAL”、“SMALLINT”、“INT”、“BIGINT”、“BOOL”、"[]BIGINT"、“JSONB”、“XML”、“TIMESTAMP”。

type RowsColumnTypeLength <- go1.8

1
2
3
4
type RowsColumnTypeLength interface {
	Rows
	ColumnTypeLength(index int) (length int64, ok bool)
}

​ RowsColumnTypeLength接口可以被 Rows 实现。如果列是变长类型,则它应返回列类型的长度。如果列不是变长类型,则应该返回 false。如果长度除系统限制外不受限制,则应返回 math.MaxInt64。以下是各种类型的返回示例:

TEXT          (math.MaxInt64, true)
varchar(10)   (10, true)
nvarchar(10)  (10, true)
decimal       (0, false)
int           (0, false)
bytea(30)     (30, true)

type RowsColumnTypeNullable <- go1.8

1
2
3
4
type RowsColumnTypeNullable interface {
	Rows
	ColumnTypeNullable(index int) (nullable, ok bool)
}

​ RowsColumnTypeNullable接口是由Rows实现的可选接口。如果已知该列可以为null,则可为空值应为true;如果已知该列不可为空,则为空值为false。如果列的可空性未知,则ok应为false。

type RowsColumnTypePrecisionScale <- go1.8

1
2
3
4
type RowsColumnTypePrecisionScale interface {
	Rows
	ColumnTypePrecisionScale(index int) (precision, scale int64, ok bool)
}

​ RowsColumnTypePrecisionScale接口是由Rows实现的可选接口。它应返回十进制类型的精度和刻度。如果不适用,则应将ok设置为false。以下是各种类型的返回值示例:

decimal(38, 4)    (38, 4, true)
int               (0, 0, false)
decimal           (math.MaxInt64, math.MaxInt64, true)

type RowsColumnTypeScanType <- go1.8

1
2
3
4
type RowsColumnTypeScanType interface {
	Rows
	ColumnTypeScanType(index int) reflect.Type
}

​ RowsColumnTypeScanType接口是由Rows实现的可选接口。它应返回可以用于扫描类型的值类型。例如,对于数据库列类型"bigint",这应返回"reflect.TypeOf(int64(0))"。

type RowsNextResultSet <- go1.8

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
type RowsNextResultSet interface {
	Rows

	// HasNextResultSet在当前结果集结束时调用,
    // 报告当前结果集之后是否还有另一个结果集。
	HasNextResultSet() bool

	// NextResultSet将驱动程序推进到下一个结果集,
    // 即使当前结果集还有剩余行。
    //
    // 当没有更多的结果集时,NextResultSet应该返回io.EOF。
	NextResultSet() error
}

​ RowsNextResultSet接口通过提供一种信号方式来扩展Rows接口,以使驱动程序前进到下一个结果集。

type SessionResetter <- go1.10

1
2
3
4
5
6
type SessionResetter interface {
	// ResetSession在连接之前执行查询时调用,
    // 如果连接之前已被使用。
    // 如果驱动程序返回ErrBadConn,则连接将被丢弃。
	ResetSession(ctx context.Context) error
}

​ SessionResetter接口可以由Conn实现,以允许驱动程序重置与连接相关的会话状态并发出坏连接信号。

type Stmt

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
type Stmt interface {
	// Close关闭预处理语句。
    //
    // 从 Go 1.1 开始,如果预处理语句正在被任何查询使用,
    // 则不会关闭预处理语句。
    //
    // 驱动程序必须确保 Close 所做的所有网络调用不会无限期地阻塞(例如,应用超时)。
	Close() error

	// NumInput 返回占位符参数的数量。
    //
    // 如果 NumInput 返回 >= 0,
    // 则 sql 包将检查调用者的参数计数,
    // 并在调用预处理语句的 Exec 或 Query 方法之前向调用者返回错误。
    //
    // 如果驱动程序不知道其占位符的数量,
    // 则 NumInput 也可以返回-1。在这种情况下,
    // sql 包将不会检查 Exec 或 Query 参数计数。
	NumInput() int

	// Exec 执行不返回行的查询,例如 INSERT 或 UPDATE。
	//
	// 已弃用:驱动程序应该实现 StmtExecContext(或另外实现)。
	Exec(args []Value) (Result, error)

	// Query 执行可能返回行的查询,例如 SELECT。
	//
	// 已弃用:驱动程序应该实现 StmtQueryContext(或另外实现)。
	Query(args []Value) (Rows, error)
}

​ Stmt接口是预处理语句。它绑定到Conn,不能被多个goroutine同时使用。

type StmtExecContext <- go1.8

1
2
3
4
5
type StmtExecContext interface {
	// ExecContext方法执行不返回行的查询,例如INSERT或UPDATE。
	// ExecContext方法必须遵守上下文超时并在取消时返回。
	ExecContext(ctx context.Context, args []NamedValue) (Result, error)
}

​ StmtExecContext接口通过提供带有上下文的Exec来增强Stmt接口。

type StmtQueryContext <- go1.8

1
2
3
4
5
type StmtQueryContext interface {
	// QueryContext方法执行可能返回行的查询,例如SELECT。
	// QueryContext方法必须遵守上下文超时并在取消时返回。
	QueryContext(ctx context.Context, args []NamedValue) (Rows, error)
}

​ StmtQueryContext接口通过提供带有上下文的Query来增强Stmt接口。

type Tx

1
2
3
4
type Tx interface {
	Commit() error
	Rollback() error
}

​ Tx 是事务。

type TxOptions <- go1.8

1
2
3
4
type TxOptions struct {
	Isolation IsolationLevel
	ReadOnly  bool
}

​ TxOptions结构体存储事务的选项。

​ 此类型应被认为与 sql.TxOptions 相同。

type Validator <- go1.15

1
2
3
4
5
type Validator interface {
	// IsValid方法在将连接放入连接池之前调用。
    // 如果返回false,则连接将被丢弃。
	IsValid() bool
}

​ Validator接口可以被 Conn 实现,以允许驱动程序表明连接是否有效或是否应丢弃。

​ 如果实现了 Validator,则驱动程序可能会从查询中返回基础错误,即使连接应该由连接池丢弃。

type Value

1
type Value any

​ Value类型是驱动程序必须能够处理的值。它可以是 nil、由数据库驱动程序的 NamedValueChecker 接口处理的类型,或是以下类型的实例

int64
float64
bool
[]byte
string
time.Time

​ 如果驱动程序支持游标,则返回的 Value 还可以在此包中实现 Rows 接口。例如,当用户选择类似于"select cursor(select * from my_table) from dual"这样的光标时。如果从选择中的 Rows 被关闭,则光标 Rows 也将被关闭。

type ValueConverter

1
2
3
4
type ValueConverter interface {
	// ConvertValue方法将一个值转换为driver.Value。
	ConvertValue(v any) (Value, error)
}

ValueConverter接口是提供 ConvertValue 方法的接口。

驱动程序包提供了 ValueConverter 的各种实现,以提供驱动程序之间的一致的转换实现。ValueConverter 有以下几个用途:

  • 将 sql 包提供的 Value 类型转换为数据库表的特定列类型,并确保其适合,例如确保特定 int64 适合于表的 uint16 列。
  • 将从数据库中给出的值转换为驱动程序 Value 类型之一。
  • 由 sql 包,在扫描中将驱动程序的 Value 类型转换为用户的类型。

type Valuer

1
2
3
4
5
type Valuer interface {
    // Value方法返回一个driver.Value。
    // Value方法不得panic。
	Value() (Value, error)
}

​ Valuer接口是提供 Value 方法的接口。

​ 实现 Valuer 接口的类型能够将自身转换为驱动程序 Value。

6 - debug

6.1 - buildinfo

buildinfo

https://pkg.go.dev/debug/buildinfo@go1.20.1

Package buildinfo provides access to information embedded in a Go binary about how it was built. This includes the Go toolchain version, and the set of modules used (for binaries built in module mode).

包buildinfo提供了对嵌入Go二进制文件中的信息的访问,了解它是如何构建的。这包括Go工具链的版本,以及所使用的模块集(对于以模块模式构建的二进制文件)。

Build information is available for the currently running binary in runtime/debug.ReadBuildInfo.

在runtime/debug.ReadBuildInfo中,当前运行的二进制文件可以获得构建信息。

常量

This section is empty.

变量

This section is empty.

函数

This section is empty.

类型

type BuildInfo

1
type BuildInfo = debug.BuildInfo

Type alias for build info. We cannot move the types here, since runtime/debug would need to import this package, which would make it a much larger dependency.

构建信息的类型别名。我们不能把类型移到这里,因为 runtime/debug 需要导入这个包,这将使它成为一个更大的依赖关系。

func Read

1
func Read(r io.ReaderAt) (*BuildInfo, error)

Read returns build information embedded in a Go binary file accessed through the given ReaderAt. Most information is only available for binaries built with module support.

Read 返回嵌入在通过给定的ReaderAt访问的Go二进制文件中的构建信息。大多数信息只适用于有模块支持的二进制文件。

func ReadFile

1
func ReadFile(name string) (info *BuildInfo, err error)

ReadFile returns build information embedded in a Go binary file at the given path. Most information is only available for binaries built with module support.

ReadFile返回嵌入在给定路径的Go二进制文件中的构建信息。大多数信息只适用于有模块支持的二进制文件。

6.2 - dwarf

dwarf

https://pkg.go.dev/debug/dwarf@go1.20.1

Package dwarf provides access to DWARF debugging information loaded from executable files, as defined in the DWARF 2.0 Standard at http://dwarfstd.org/doc/dwarf-2.0.0.pdf.

Security

This package is not designed to be hardened against adversarial inputs, and is outside the scope of https://go.dev/security/policy. In particular, only basic validation is done when parsing object files. As such, care should be taken when parsing untrusted inputs, as parsing malformed files may consume significant resources, or cause panics.

常量

This section is empty.

变量

View Source

1
var ErrUnknownPC = errors.New("ErrUnknownPC")

ErrUnknownPC is the error returned by LineReader.ScanPC when the seek PC is not covered by any entry in the line table.

函数

This section is empty.

类型

type AddrType

1
2
3
type AddrType struct {
	BasicType
}

An AddrType represents a machine address type.

type ArrayType

1
2
3
4
5
6
type ArrayType struct {
	CommonType
	Type          Type
	StrideBitSize int64 // if > 0, number of bits to hold each element
	Count         int64 // if == -1, an incomplete array, like char x[].
}

An ArrayType represents a fixed size array type.

(*ArrayType) Size

1
func (t *ArrayType) Size() int64

(*ArrayType) String

1
func (t *ArrayType) String() string

type Attr

1
type Attr uint32

An Attr identifies the attribute type in a DWARF Entry’s Field.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
const (
	AttrSibling        Attr = 0x01
	AttrLocation       Attr = 0x02
	AttrName           Attr = 0x03
	AttrOrdering       Attr = 0x09
	AttrByteSize       Attr = 0x0B
	AttrBitOffset      Attr = 0x0C
	AttrBitSize        Attr = 0x0D
	AttrStmtList       Attr = 0x10
	AttrLowpc          Attr = 0x11
	AttrHighpc         Attr = 0x12
	AttrLanguage       Attr = 0x13
	AttrDiscr          Attr = 0x15
	AttrDiscrValue     Attr = 0x16
	AttrVisibility     Attr = 0x17
	AttrImport         Attr = 0x18
	AttrStringLength   Attr = 0x19
	AttrCommonRef      Attr = 0x1A
	AttrCompDir        Attr = 0x1B
	AttrConstValue     Attr = 0x1C
	AttrContainingType Attr = 0x1D
	AttrDefaultValue   Attr = 0x1E
	AttrInline         Attr = 0x20
	AttrIsOptional     Attr = 0x21
	AttrLowerBound     Attr = 0x22
	AttrProducer       Attr = 0x25
	AttrPrototyped     Attr = 0x27
	AttrReturnAddr     Attr = 0x2A
	AttrStartScope     Attr = 0x2C
	AttrStrideSize     Attr = 0x2E
	AttrUpperBound     Attr = 0x2F
	AttrAbstractOrigin Attr = 0x31
	AttrAccessibility  Attr = 0x32
	AttrAddrClass      Attr = 0x33
	AttrArtificial     Attr = 0x34
	AttrBaseTypes      Attr = 0x35
	AttrCalling        Attr = 0x36
	AttrCount          Attr = 0x37
	AttrDataMemberLoc  Attr = 0x38
	AttrDeclColumn     Attr = 0x39
	AttrDeclFile       Attr = 0x3A
	AttrDeclLine       Attr = 0x3B
	AttrDeclaration    Attr = 0x3C
	AttrDiscrList      Attr = 0x3D
	AttrEncoding       Attr = 0x3E
	AttrExternal       Attr = 0x3F
	AttrFrameBase      Attr = 0x40
	AttrFriend         Attr = 0x41
	AttrIdentifierCase Attr = 0x42
	AttrMacroInfo      Attr = 0x43
	AttrNamelistItem   Attr = 0x44
	AttrPriority       Attr = 0x45
	AttrSegment        Attr = 0x46
	AttrSpecification  Attr = 0x47
	AttrStaticLink     Attr = 0x48
	AttrType           Attr = 0x49
	AttrUseLocation    Attr = 0x4A
	AttrVarParam       Attr = 0x4B
	AttrVirtuality     Attr = 0x4C
	AttrVtableElemLoc  Attr = 0x4D
	// The following are new in DWARF 3.
	AttrAllocated     Attr = 0x4E
	AttrAssociated    Attr = 0x4F
	AttrDataLocation  Attr = 0x50
	AttrStride        Attr = 0x51
	AttrEntrypc       Attr = 0x52
	AttrUseUTF8       Attr = 0x53
	AttrExtension     Attr = 0x54
	AttrRanges        Attr = 0x55
	AttrTrampoline    Attr = 0x56
	AttrCallColumn    Attr = 0x57
	AttrCallFile      Attr = 0x58
	AttrCallLine      Attr = 0x59
	AttrDescription   Attr = 0x5A
	AttrBinaryScale   Attr = 0x5B
	AttrDecimalScale  Attr = 0x5C
	AttrSmall         Attr = 0x5D
	AttrDecimalSign   Attr = 0x5E
	AttrDigitCount    Attr = 0x5F
	AttrPictureString Attr = 0x60
	AttrMutable       Attr = 0x61
	AttrThreadsScaled Attr = 0x62
	AttrExplicit      Attr = 0x63
	AttrObjectPointer Attr = 0x64
	AttrEndianity     Attr = 0x65
	AttrElemental     Attr = 0x66
	AttrPure          Attr = 0x67
	AttrRecursive     Attr = 0x68
	// The following are new in DWARF 4.
	AttrSignature      Attr = 0x69
	AttrMainSubprogram Attr = 0x6A
	AttrDataBitOffset  Attr = 0x6B
	AttrConstExpr      Attr = 0x6C
	AttrEnumClass      Attr = 0x6D
	AttrLinkageName    Attr = 0x6E
	// The following are new in DWARF 5.
	AttrStringLengthBitSize  Attr = 0x6F
	AttrStringLengthByteSize Attr = 0x70
	AttrRank                 Attr = 0x71
	AttrStrOffsetsBase       Attr = 0x72
	AttrAddrBase             Attr = 0x73
	AttrRnglistsBase         Attr = 0x74
	AttrDwoName              Attr = 0x76
	AttrReference            Attr = 0x77
	AttrRvalueReference      Attr = 0x78
	AttrMacros               Attr = 0x79
	AttrCallAllCalls         Attr = 0x7A
	AttrCallAllSourceCalls   Attr = 0x7B
	AttrCallAllTailCalls     Attr = 0x7C
	AttrCallReturnPC         Attr = 0x7D
	AttrCallValue            Attr = 0x7E
	AttrCallOrigin           Attr = 0x7F
	AttrCallParameter        Attr = 0x80
	AttrCallPC               Attr = 0x81
	AttrCallTailCall         Attr = 0x82
	AttrCallTarget           Attr = 0x83
	AttrCallTargetClobbered  Attr = 0x84
	AttrCallDataLocation     Attr = 0x85
	AttrCallDataValue        Attr = 0x86
	AttrNoreturn             Attr = 0x87
	AttrAlignment            Attr = 0x88
	AttrExportSymbols        Attr = 0x89
	AttrDeleted              Attr = 0x8A
	AttrDefaulted            Attr = 0x8B
	AttrLoclistsBase         Attr = 0x8C
)

(Attr) GoString

1
func (a Attr) GoString() string

(Attr) String

1
func (i Attr) String() string

type BasicType

1
2
3
4
5
6
type BasicType struct {
	CommonType
	BitSize       int64
	BitOffset     int64
	DataBitOffset int64
}

A BasicType holds fields common to all basic types.

See the documentation for StructField for more info on the interpretation of the BitSize/BitOffset/DataBitOffset fields.

(*BasicType) Basic

1
func (b *BasicType) Basic() *BasicType

(*BasicType) String

1
func (t *BasicType) String() string

type BoolType

1
2
3
type BoolType struct {
	BasicType
}

A BoolType represents a boolean type.

type CharType

1
2
3
type CharType struct {
	BasicType
}

A CharType represents a signed character type.

type Class <- go1.5

1
type Class int

A Class is the DWARF 4 class of an attribute value.

In general, a given attribute’s value may take on one of several possible classes defined by DWARF, each of which leads to a slightly different interpretation of the attribute.

DWARF version 4 distinguishes attribute value classes more finely than previous versions of DWARF. The reader will disambiguate coarser classes from earlier versions of DWARF into the appropriate DWARF 4 class. For example, DWARF 2 uses “constant” for constants as well as all types of section offsets, but the reader will canonicalize attributes in DWARF 2 files that refer to section offsets to one of the Class*Ptr classes, even though these classes were only defined in DWARF 3.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
const (
	// ClassUnknown represents values of unknown DWARF class.
	ClassUnknown Class = iota

	// ClassAddress represents values of type uint64 that are
	// addresses on the target machine.
	ClassAddress

	// ClassBlock represents values of type []byte whose
	// interpretation depends on the attribute.
	ClassBlock

	// ClassConstant represents values of type int64 that are
	// constants. The interpretation of this constant depends on
	// the attribute.
	ClassConstant

	// ClassExprLoc represents values of type []byte that contain
	// an encoded DWARF expression or location description.
	ClassExprLoc

	// ClassFlag represents values of type bool.
	ClassFlag

	// ClassLinePtr represents values that are an int64 offset
	// into the "line" section.
	ClassLinePtr

	// ClassLocListPtr represents values that are an int64 offset
	// into the "loclist" section.
	ClassLocListPtr

	// ClassMacPtr represents values that are an int64 offset into
	// the "mac" section.
	ClassMacPtr

	// ClassRangeListPtr represents values that are an int64 offset into
	// the "rangelist" section.
	ClassRangeListPtr

	// ClassReference represents values that are an Offset offset
	// of an Entry in the info section (for use with Reader.Seek).
	// The DWARF specification combines ClassReference and
	// ClassReferenceSig into class "reference".
	ClassReference

	// ClassReferenceSig represents values that are a uint64 type
	// signature referencing a type Entry.
	ClassReferenceSig

	// ClassString represents values that are strings. If the
	// compilation unit specifies the AttrUseUTF8 flag (strongly
	// recommended), the string value will be encoded in UTF-8.
	// Otherwise, the encoding is unspecified.
	ClassString

	// ClassReferenceAlt represents values of type int64 that are
	// an offset into the DWARF "info" section of an alternate
	// object file.
	ClassReferenceAlt

	// ClassStringAlt represents values of type int64 that are an
	// offset into the DWARF string section of an alternate object
	// file.
	ClassStringAlt

	// ClassAddrPtr represents values that are an int64 offset
	// into the "addr" section.
	ClassAddrPtr

	// ClassLocList represents values that are an int64 offset
	// into the "loclists" section.
	ClassLocList

	// ClassRngList represents values that are a uint64 offset
	// from the base of the "rnglists" section.
	ClassRngList

	// ClassRngListsPtr represents values that are an int64 offset
	// into the "rnglists" section. These are used as the base for
	// ClassRngList values.
	ClassRngListsPtr

	// ClassStrOffsetsPtr represents values that are an int64
	// offset into the "str_offsets" section.
	ClassStrOffsetsPtr
)

(Class) GoString <- go1.5

1
func (i Class) GoString() string

(Class) String <- go1.5

1
func (i Class) String() string

type CommonType

1
2
3
4
type CommonType struct {
	ByteSize int64  // size of value of this type, in bytes
	Name     string // name that can be used to refer to type
}

A CommonType holds fields common to multiple types. If a field is not known or not applicable for a given type, the zero value is used.

(*CommonType) Common

1
func (c *CommonType) Common() *CommonType

(*CommonType) Size

1
func (c *CommonType) Size() int64

type ComplexType

1
2
3
type ComplexType struct {
	BasicType
}

A ComplexType represents a complex floating point type.

type Data

1
2
3
type Data struct {
	// contains filtered or unexported fields
}

Data represents the DWARF debugging information loaded from an executable file (for example, an ELF or Mach-O executable).

func New

1
func New(abbrev, aranges, frame, info, line, pubnames, ranges, str []byte) (*Data, error)

New returns a new Data object initialized from the given parameters. Rather than calling this function directly, clients should typically use the DWARF method of the File type of the appropriate package debug/elf, debug/macho, or debug/pe.

The []byte arguments are the data from the corresponding debug section in the object file; for example, for an ELF object, abbrev is the contents of the “.debug_abbrev” section.

(*Data) AddSection <- go1.14

1
func (d *Data) AddSection(name string, contents []byte) error

AddSection adds another DWARF section by name. The name should be a DWARF section name such as “.debug_addr”, “.debug_str_offsets”, and so forth. This approach is used for new DWARF sections added in DWARF 5 and later.

(*Data) AddTypes <- go1.3

1
func (d *Data) AddTypes(name string, types []byte) error

AddTypes will add one .debug_types section to the DWARF data. A typical object with DWARF version 4 debug info will have multiple .debug_types sections. The name is used for error reporting only, and serves to distinguish one .debug_types section from another.

(*Data) LineReader <- go1.5

1
func (d *Data) LineReader(cu *Entry) (*LineReader, error)

LineReader returns a new reader for the line table of compilation unit cu, which must be an Entry with tag TagCompileUnit.

If this compilation unit has no line table, it returns nil, nil.

(*Data) Ranges <- go1.7

1
func (d *Data) Ranges(e *Entry) ([][2]uint64, error)

Ranges returns the PC ranges covered by e, a slice of [low,high) pairs. Only some entry types, such as TagCompileUnit or TagSubprogram, have PC ranges; for others, this will return nil with no error.

(*Data) Reader

1
func (d *Data) Reader() *Reader

Reader returns a new Reader for Data. The reader is positioned at byte offset 0 in the DWARF “info” section.

(*Data) Type

1
func (d *Data) Type(off Offset) (Type, error)

Type reads the type at off in the DWARF “info” section.

type DecodeError

1
2
3
4
5
type DecodeError struct {
	Name   string
	Offset Offset
	Err    string
}

(DecodeError) Error

1
func (e DecodeError) Error() string

type DotDotDotType

1
2
3
type DotDotDotType struct {
	CommonType
}

A DotDotDotType represents the variadic … function parameter.

(*DotDotDotType) String

1
func (t *DotDotDotType) String() string

type Entry

1
2
3
4
5
6
type Entry struct {
	Offset   Offset // offset of Entry in DWARF info
	Tag      Tag    // tag (kind of Entry)
	Children bool   // whether Entry is followed by children
	Field    []Field
}

An entry is a sequence of attribute/value pairs.

(*Entry) AttrField <- go1.5

1
func (e *Entry) AttrField(a Attr) *Field

AttrField returns the Field associated with attribute Attr in Entry, or nil if there is no such attribute.

(*Entry) Val

1
func (e *Entry) Val(a Attr) any

Val returns the value associated with attribute Attr in Entry, or nil if there is no such attribute.

A common idiom is to merge the check for nil return with the check that the value has the expected dynamic type, as in:

v, ok := e.Val(AttrSibling).(int64)

type EnumType

1
2
3
4
5
type EnumType struct {
	CommonType
	EnumName string
	Val      []*EnumValue
}

An EnumType represents an enumerated type. The only indication of its native integer type is its ByteSize (inside CommonType).

(*EnumType) String

1
func (t *EnumType) String() string

type EnumValue

1
2
3
4
type EnumValue struct {
	Name string
	Val  int64
}

An EnumValue represents a single enumeration value.

type Field

1
2
3
4
5
type Field struct {
	Attr  Attr
	Val   any
	Class Class
}

A Field is a single attribute/value pair in an Entry.

A value can be one of several “attribute classes” defined by DWARF. The Go types corresponding to each class are:

DWARF class       Go type        Class
-----------       -------        -----
address           uint64         ClassAddress
block             []byte         ClassBlock
constant          int64          ClassConstant
flag              bool           ClassFlag
reference
  to info         dwarf.Offset   ClassReference
  to type unit    uint64         ClassReferenceSig
string            string         ClassString
exprloc           []byte         ClassExprLoc
lineptr           int64          ClassLinePtr
loclistptr        int64          ClassLocListPtr
macptr            int64          ClassMacPtr
rangelistptr      int64          ClassRangeListPtr

For unrecognized or vendor-defined attributes, Class may be ClassUnknown.

type FloatType

1
2
3
type FloatType struct {
	BasicType
}

A FloatType represents a floating point type.

type FuncType

1
2
3
4
5
type FuncType struct {
	CommonType
	ReturnType Type
	ParamType  []Type
}

A FuncType represents a function type.

(*FuncType) String

1
func (t *FuncType) String() string

type IntType

1
2
3
type IntType struct {
	BasicType
}

An IntType represents a signed integer type.

type LineEntry <- go1.5

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
type LineEntry struct {
	// Address is the program-counter value of a machine
	// instruction generated by the compiler. This LineEntry
	// applies to each instruction from Address to just before the
	// Address of the next LineEntry.
	Address uint64

	// OpIndex is the index of an operation within a VLIW
	// instruction. The index of the first operation is 0. For
	// non-VLIW architectures, it will always be 0. Address and
	// OpIndex together form an operation pointer that can
	// reference any individual operation within the instruction
	// stream.
	OpIndex int

	// File is the source file corresponding to these
	// instructions.
	File *LineFile

	// Line is the source code line number corresponding to these
	// instructions. Lines are numbered beginning at 1. It may be
	// 0 if these instructions cannot be attributed to any source
	// line.
	Line int

	// Column is the column number within the source line of these
	// instructions. Columns are numbered beginning at 1. It may
	// be 0 to indicate the "left edge" of the line.
	Column int

	// IsStmt indicates that Address is a recommended breakpoint
	// location, such as the beginning of a line, statement, or a
	// distinct subpart of a statement.
	IsStmt bool

	// BasicBlock indicates that Address is the beginning of a
	// basic block.
	BasicBlock bool

	// PrologueEnd indicates that Address is one (of possibly
	// many) PCs where execution should be suspended for a
	// breakpoint on entry to the containing function.
	//
	// Added in DWARF 3.
	PrologueEnd bool

	// EpilogueBegin indicates that Address is one (of possibly
	// many) PCs where execution should be suspended for a
	// breakpoint on exit from this function.
	//
	// Added in DWARF 3.
	EpilogueBegin bool

	// ISA is the instruction set architecture for these
	// instructions. Possible ISA values should be defined by the
	// applicable ABI specification.
	//
	// Added in DWARF 3.
	ISA int

	// Discriminator is an arbitrary integer indicating the block
	// to which these instructions belong. It serves to
	// distinguish among multiple blocks that may all have with
	// the same source file, line, and column. Where only one
	// block exists for a given source position, it should be 0.
	//
	// Added in DWARF 3.
	Discriminator int

	// EndSequence indicates that Address is the first byte after
	// the end of a sequence of target machine instructions. If it
	// is set, only this and the Address field are meaningful. A
	// line number table may contain information for multiple
	// potentially disjoint instruction sequences. The last entry
	// in a line table should always have EndSequence set.
	EndSequence bool
}

A LineEntry is a row in a DWARF line table.

type LineFile <- go1.5

1
2
3
4
5
type LineFile struct {
	Name   string
	Mtime  uint64 // Implementation defined modification time, or 0 if unknown
	Length int    // File length, or 0 if unknown
}

A LineFile is a source file referenced by a DWARF line table entry.

type LineReader <- go1.5

1
2
3
type LineReader struct {
	// contains filtered or unexported fields
}

A LineReader reads a sequence of LineEntry structures from a DWARF “line” section for a single compilation unit. LineEntries occur in order of increasing PC and each LineEntry gives metadata for the instructions from that LineEntry’s PC to just before the next LineEntry’s PC. The last entry will have its EndSequence field set.

(*LineReader) Files <- go1.14

1
func (r *LineReader) Files() []*LineFile

Files returns the file name table of this compilation unit as of the current position in the line table. The file name table may be referenced from attributes in this compilation unit such as AttrDeclFile.

Entry 0 is always nil, since file index 0 represents “no file”.

The file name table of a compilation unit is not fixed. Files returns the file table as of the current position in the line table. This may contain more entries than the file table at an earlier position in the line table, though existing entries never change.

(*LineReader) Next <- go1.5

1
func (r *LineReader) Next(entry *LineEntry) error

Next sets *entry to the next row in this line table and moves to the next row. If there are no more entries and the line table is properly terminated, it returns io.EOF.

Rows are always in order of increasing entry.Address, but entry.Line may go forward or backward.

(*LineReader) Reset <- go1.5

1
func (r *LineReader) Reset()

Reset repositions the line table reader at the beginning of the line table.

(*LineReader) Seek <- go1.5

1
func (r *LineReader) Seek(pos LineReaderPos)

Seek restores the line table reader to a position returned by Tell.

The argument pos must have been returned by a call to Tell on this line table.

(*LineReader) SeekPC <- go1.5

1
func (r *LineReader) SeekPC(pc uint64, entry *LineEntry) error

SeekPC sets *entry to the LineEntry that includes pc and positions the reader on the next entry in the line table. If necessary, this will seek backwards to find pc.

If pc is not covered by any entry in this line table, SeekPC returns ErrUnknownPC. In this case, *entry and the final seek position are unspecified.

Note that DWARF line tables only permit sequential, forward scans. Hence, in the worst case, this takes time linear in the size of the line table. If the caller wishes to do repeated fast PC lookups, it should build an appropriate index of the line table.

(*LineReader) Tell <- go1.5

1
func (r *LineReader) Tell() LineReaderPos

Tell returns the current position in the line table.

type LineReaderPos <- go1.5

1
2
3
type LineReaderPos struct {
	// contains filtered or unexported fields
}

A LineReaderPos represents a position in a line table.

type Offset

1
type Offset uint32

An Offset represents the location of an Entry within the DWARF info. (See Reader.Seek.)

type PtrType

1
2
3
4
type PtrType struct {
	CommonType
	Type Type
}

A PtrType represents a pointer type.

(*PtrType) String

1
func (t *PtrType) String() string

type QualType

1
2
3
4
5
type QualType struct {
	CommonType
	Qual string
	Type Type
}

A QualType represents a type that has the C/C++ “const”, “restrict”, or “volatile” qualifier.

(*QualType) Size

1
func (t *QualType) Size() int64

(*QualType) String

1
func (t *QualType) String() string

type Reader

1
2
3
type Reader struct {
	// contains filtered or unexported fields
}

A Reader allows reading Entry structures from a DWARF “info” section. The Entry structures are arranged in a tree. The Reader’s Next function return successive entries from a pre-order traversal of the tree. If an entry has children, its Children field will be true, and the children follow, terminated by an Entry with Tag 0.

(*Reader) AddressSize <- go1.5

1
func (r *Reader) AddressSize() int

AddressSize returns the size in bytes of addresses in the current compilation unit.

(*Reader) ByteOrder <- go1.14

1
func (r *Reader) ByteOrder() binary.ByteOrder

ByteOrder returns the byte order in the current compilation unit.

(*Reader) Next

1
func (r *Reader) Next() (*Entry, error)

Next reads the next entry from the encoded entry stream. It returns nil, nil when it reaches the end of the section. It returns an error if the current offset is invalid or the data at the offset cannot be decoded as a valid Entry.

(*Reader) Seek

1
func (r *Reader) Seek(off Offset)

Seek positions the Reader at offset off in the encoded entry stream. Offset 0 can be used to denote the first entry.

(*Reader) SeekPC <- go1.7

1
func (r *Reader) SeekPC(pc uint64) (*Entry, error)

SeekPC returns the Entry for the compilation unit that includes pc, and positions the reader to read the children of that unit. If pc is not covered by any unit, SeekPC returns ErrUnknownPC and the position of the reader is undefined.

Because compilation units can describe multiple regions of the executable, in the worst case SeekPC must search through all the ranges in all the compilation units. Each call to SeekPC starts the search at the compilation unit of the last call, so in general looking up a series of PCs will be faster if they are sorted. If the caller wishes to do repeated fast PC lookups, it should build an appropriate index using the Ranges method.

(*Reader) SkipChildren

1
func (r *Reader) SkipChildren()

SkipChildren skips over the child entries associated with the last Entry returned by Next. If that Entry did not have children or Next has not been called, SkipChildren is a no-op.

type StructField

1
2
3
4
5
6
7
8
9
type StructField struct {
	Name          string
	Type          Type
	ByteOffset    int64
	ByteSize      int64 // usually zero; use Type.Size() for normal fields
	BitOffset     int64
	DataBitOffset int64
	BitSize       int64 // zero if not a bit field
}

A StructField represents a field in a struct, union, or C++ class type.

Bit Fields

The BitSize, BitOffset, and DataBitOffset fields describe the bit size and offset of data members declared as bit fields in C/C++ struct/union/class types.

BitSize is the number of bits in the bit field.

DataBitOffset, if non-zero, is the number of bits from the start of the enclosing entity (e.g. containing struct/class/union) to the start of the bit field. This corresponds to the DW_AT_data_bit_offset DWARF attribute that was introduced in DWARF 4.

BitOffset, if non-zero, is the number of bits between the most significant bit of the storage unit holding the bit field to the most significant bit of the bit field. Here “storage unit” is the type name before the bit field (for a field “unsigned x:17”, the storage unit is “unsigned”). BitOffset values can vary depending on the endianness of the system. BitOffset corresponds to the DW_AT_bit_offset DWARF attribute that was deprecated in DWARF 4 and removed in DWARF 5.

At most one of DataBitOffset and BitOffset will be non-zero; DataBitOffset/BitOffset will only be non-zero if BitSize is non-zero. Whether a C compiler uses one or the other will depend on compiler vintage and command line options.

Here is an example of C/C++ bit field use, along with what to expect in terms of DWARF bit offset info. Consider this code:

struct S {
	int q;
	int j:5;
	int k:6;
	int m:5;
	int n:8;
} s;

For the code above, one would expect to see the following for DW_AT_bit_offset values (using GCC 8):

       Little   |     Big
       Endian   |    Endian
                |
"j":     27     |     0
"k":     21     |     5
"m":     16     |     11
"n":     8      |     16

Note that in the above the offsets are purely with respect to the containing storage unit for j/k/m/n – these values won’t vary based on the size of prior data members in the containing struct.

If the compiler emits DW_AT_data_bit_offset, the expected values would be:

"j":     32
"k":     37
"m":     43
"n":     48

Here the value 32 for “j” reflects the fact that the bit field is preceded by other data members (recall that DW_AT_data_bit_offset values are relative to the start of the containing struct). Hence DW_AT_data_bit_offset values can be quite large for structs with many fields.

DWARF also allow for the possibility of base types that have non-zero bit size and bit offset, so this information is also captured for base types, but it is worth noting that it is not possible to trigger this behavior using mainstream languages.

type StructType

1
2
3
4
5
6
7
type StructType struct {
	CommonType
	StructName string
	Kind       string // "struct", "union", or "class".
	Field      []*StructField
	Incomplete bool // if true, struct, union, class is declared but not defined
}

A StructType represents a struct, union, or C++ class type.

(*StructType) Defn

1
func (t *StructType) Defn() string

(*StructType) String

1
func (t *StructType) String() string

type Tag

1
type Tag uint32

A Tag is the classification (the type) of an Entry.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
const (
	TagArrayType              Tag = 0x01
	TagClassType              Tag = 0x02
	TagEntryPoint             Tag = 0x03
	TagEnumerationType        Tag = 0x04
	TagFormalParameter        Tag = 0x05
	TagImportedDeclaration    Tag = 0x08
	TagLabel                  Tag = 0x0A
	TagLexDwarfBlock          Tag = 0x0B
	TagMember                 Tag = 0x0D
	TagPointerType            Tag = 0x0F
	TagReferenceType          Tag = 0x10
	TagCompileUnit            Tag = 0x11
	TagStringType             Tag = 0x12
	TagStructType             Tag = 0x13
	TagSubroutineType         Tag = 0x15
	TagTypedef                Tag = 0x16
	TagUnionType              Tag = 0x17
	TagUnspecifiedParameters  Tag = 0x18
	TagVariant                Tag = 0x19
	TagCommonDwarfBlock       Tag = 0x1A
	TagCommonInclusion        Tag = 0x1B
	TagInheritance            Tag = 0x1C
	TagInlinedSubroutine      Tag = 0x1D
	TagModule                 Tag = 0x1E
	TagPtrToMemberType        Tag = 0x1F
	TagSetType                Tag = 0x20
	TagSubrangeType           Tag = 0x21
	TagWithStmt               Tag = 0x22
	TagAccessDeclaration      Tag = 0x23
	TagBaseType               Tag = 0x24
	TagCatchDwarfBlock        Tag = 0x25
	TagConstType              Tag = 0x26
	TagConstant               Tag = 0x27
	TagEnumerator             Tag = 0x28
	TagFileType               Tag = 0x29
	TagFriend                 Tag = 0x2A
	TagNamelist               Tag = 0x2B
	TagNamelistItem           Tag = 0x2C
	TagPackedType             Tag = 0x2D
	TagSubprogram             Tag = 0x2E
	TagTemplateTypeParameter  Tag = 0x2F
	TagTemplateValueParameter Tag = 0x30
	TagThrownType             Tag = 0x31
	TagTryDwarfBlock          Tag = 0x32
	TagVariantPart            Tag = 0x33
	TagVariable               Tag = 0x34
	TagVolatileType           Tag = 0x35
	// The following are new in DWARF 3.
	TagDwarfProcedure  Tag = 0x36
	TagRestrictType    Tag = 0x37
	TagInterfaceType   Tag = 0x38
	TagNamespace       Tag = 0x39
	TagImportedModule  Tag = 0x3A
	TagUnspecifiedType Tag = 0x3B
	TagPartialUnit     Tag = 0x3C
	TagImportedUnit    Tag = 0x3D
	TagMutableType     Tag = 0x3E // Later removed from DWARF.
	TagCondition       Tag = 0x3F
	TagSharedType      Tag = 0x40
	// The following are new in DWARF 4.
	TagTypeUnit            Tag = 0x41
	TagRvalueReferenceType Tag = 0x42
	TagTemplateAlias       Tag = 0x43
	// The following are new in DWARF 5.
	TagCoarrayType       Tag = 0x44
	TagGenericSubrange   Tag = 0x45
	TagDynamicType       Tag = 0x46
	TagAtomicType        Tag = 0x47
	TagCallSite          Tag = 0x48
	TagCallSiteParameter Tag = 0x49
	TagSkeletonUnit      Tag = 0x4A
	TagImmutableType     Tag = 0x4B
)

(Tag) GoString

1
func (t Tag) GoString() string

(Tag) String

1
func (i Tag) String() string

type Type

1
2
3
4
5
type Type interface {
	Common() *CommonType
	String() string
	Size() int64
}

A Type conventionally represents a pointer to any of the specific Type structures (CharType, StructType, etc.).

type TypedefType

1
2
3
4
type TypedefType struct {
	CommonType
	Type Type
}

A TypedefType represents a named type.

(*TypedefType) Size

1
func (t *TypedefType) Size() int64

(*TypedefType) String

1
func (t *TypedefType) String() string

type UcharType

1
2
3
type UcharType struct {
	BasicType
}

A UcharType represents an unsigned character type.

type UintType

1
2
3
type UintType struct {
	BasicType
}

A UintType represents an unsigned integer type.

type UnspecifiedType <- go1.4

1
2
3
type UnspecifiedType struct {
	BasicType
}

An UnspecifiedType represents an implicit, unknown, ambiguous or nonexistent type.

type UnsupportedType <- go1.13

1
2
3
4
type UnsupportedType struct {
	CommonType
	Tag Tag
}

An UnsupportedType is a placeholder returned in situations where we encounter a type that isn’t supported.

(*UnsupportedType) String <- go1.13

1
func (t *UnsupportedType) String() string

type VoidType

1
2
3
type VoidType struct {
	CommonType
}

A VoidType represents the C void type.

(*VoidType) String

1
func (t *VoidType) String() string

6.3 - elf

elf

https://pkg.go.dev/debug/elf@go1.20.1

Package elf implements access to ELF object files.

Security

This package is not designed to be hardened against adversarial inputs, and is outside the scope of https://go.dev/security/policy. In particular, only basic validation is done when parsing object files. As such, care should be taken when parsing untrusted inputs, as parsing malformed files may consume significant resources, or cause panics.

常量

View Source

1
2
3
4
5
6
7
8
9
const (
	EI_CLASS      = 4  /* Class of machine. */
	EI_DATA       = 5  /* Data format. */
	EI_VERSION    = 6  /* ELF format version. */
	EI_OSABI      = 7  /* Operating system / ABI identification */
	EI_ABIVERSION = 8  /* ABI version */
	EI_PAD        = 9  /* Start of padding (per SVR4 ABI). */
	EI_NIDENT     = 16 /* Size of e_ident array. */
)

Indexes into the Header.Ident array.

View Source

1
const ARM_MAGIC_TRAMP_NUMBER = 0x5c000003

Magic number for the elf trampoline, chosen wisely to be an immediate value.

View Source

1
const ELFMAG = "\177ELF"

Initial magic number for ELF files.

View Source

1
const Sym32Size = 16

View Source

1
const Sym64Size = 24

变量

View Source

1
var ErrNoSymbols = errors.New("no symbol section")

ErrNoSymbols is returned by File.Symbols and File.DynamicSymbols if there is no such section in the File.

函数

func R_INFO

1
func R_INFO(sym, typ uint32) uint64

func R_INFO32

1
func R_INFO32(sym, typ uint32) uint32

func R_SYM32

1
func R_SYM32(info uint32) uint32

func R_SYM64

1
func R_SYM64(info uint64) uint32

func R_TYPE32

1
func R_TYPE32(info uint32) uint32

func R_TYPE64

1
func R_TYPE64(info uint64) uint32

func ST_INFO

1
func ST_INFO(bind SymBind, typ SymType) uint8

类型

type Chdr32 <- go1.6

1
2
3
4
5
type Chdr32 struct {
	Type      uint32
	Size      uint32
	Addralign uint32
}

ELF32 Compression header.

type Chdr64 <- go1.6

1
2
3
4
5
6
7
type Chdr64 struct {
	Type uint32

	Size      uint64
	Addralign uint64
	// contains filtered or unexported fields
}

ELF64 Compression header.

type Class

1
type Class byte

Class is found in Header.Ident[EI_CLASS] and Header.Class.

1
2
3
4
5
const (
	ELFCLASSNONE Class = 0 /* Unknown class. */
	ELFCLASS32   Class = 1 /* 32-bit architecture. */
	ELFCLASS64   Class = 2 /* 64-bit architecture. */
)

(Class) GoString

1
func (i Class) GoString() string

(Class) String

1
func (i Class) String() string

type CompressionType <- go1.6

1
type CompressionType int

Section compression type.

1
2
3
4
5
6
7
const (
	COMPRESS_ZLIB   CompressionType = 1          /* ZLIB compression. */
	COMPRESS_LOOS   CompressionType = 0x60000000 /* First OS-specific. */
	COMPRESS_HIOS   CompressionType = 0x6fffffff /* Last OS-specific. */
	COMPRESS_LOPROC CompressionType = 0x70000000 /* First processor-specific type. */
	COMPRESS_HIPROC CompressionType = 0x7fffffff /* Last processor-specific type. */
)

(CompressionType) GoString <- go1.6

1
func (i CompressionType) GoString() string

(CompressionType) String <- go1.6

1
func (i CompressionType) String() string

type Data

1
type Data byte

Data is found in Header.Ident[EI_DATA] and Header.Data.

1
2
3
4
5
const (
	ELFDATANONE Data = 0 /* Unknown data format. */
	ELFDATA2LSB Data = 1 /* 2's complement little-endian. */
	ELFDATA2MSB Data = 2 /* 2's complement big-endian. */
)

(Data) GoString

1
func (i Data) GoString() string

(Data) String

1
func (i Data) String() string

type Dyn32

1
2
3
4
type Dyn32 struct {
	Tag int32  /* Entry type. */
	Val uint32 /* Integer/Address value. */
}

ELF32 Dynamic structure. The “.dynamic” section contains an array of them.

type Dyn64

1
2
3
4
type Dyn64 struct {
	Tag int64  /* Entry type. */
	Val uint64 /* Integer/address value */
}

ELF64 Dynamic structure. The “.dynamic” section contains an array of them.

type DynFlag

1
type DynFlag int

DT_FLAGS values.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
const (
	DF_ORIGIN DynFlag = 0x0001 /* Indicates that the object being loaded may
	   make reference to the
	   $ORIGIN substitution string */
	DF_SYMBOLIC DynFlag = 0x0002 /* Indicates "symbolic" linking. */
	DF_TEXTREL  DynFlag = 0x0004 /* Indicates there may be relocations in non-writable segments. */
	DF_BIND_NOW DynFlag = 0x0008 /* Indicates that the dynamic linker should
	   process all relocations for the object
	   containing this entry before transferring
	   control to the program. */
	DF_STATIC_TLS DynFlag = 0x0010 /* Indicates that the shared object or
	   executable contains code using a static
	   thread-local storage scheme. */
)

(DynFlag) GoString

1
func (i DynFlag) GoString() string

(DynFlag) String

1
func (i DynFlag) String() string

type DynTag

1
type DynTag int

Dyn.Tag

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
const (
	DT_NULL         DynTag = 0  /* Terminating entry. */
	DT_NEEDED       DynTag = 1  /* String table offset of a needed shared library. */
	DT_PLTRELSZ     DynTag = 2  /* Total size in bytes of PLT relocations. */
	DT_PLTGOT       DynTag = 3  /* Processor-dependent address. */
	DT_HASH         DynTag = 4  /* Address of symbol hash table. */
	DT_STRTAB       DynTag = 5  /* Address of string table. */
	DT_SYMTAB       DynTag = 6  /* Address of symbol table. */
	DT_RELA         DynTag = 7  /* Address of ElfNN_Rela relocations. */
	DT_RELASZ       DynTag = 8  /* Total size of ElfNN_Rela relocations. */
	DT_RELAENT      DynTag = 9  /* Size of each ElfNN_Rela relocation entry. */
	DT_STRSZ        DynTag = 10 /* Size of string table. */
	DT_SYMENT       DynTag = 11 /* Size of each symbol table entry. */
	DT_INIT         DynTag = 12 /* Address of initialization function. */
	DT_FINI         DynTag = 13 /* Address of finalization function. */
	DT_SONAME       DynTag = 14 /* String table offset of shared object name. */
	DT_RPATH        DynTag = 15 /* String table offset of library path. [sup] */
	DT_SYMBOLIC     DynTag = 16 /* Indicates "symbolic" linking. [sup] */
	DT_REL          DynTag = 17 /* Address of ElfNN_Rel relocations. */
	DT_RELSZ        DynTag = 18 /* Total size of ElfNN_Rel relocations. */
	DT_RELENT       DynTag = 19 /* Size of each ElfNN_Rel relocation. */
	DT_PLTREL       DynTag = 20 /* Type of relocation used for PLT. */
	DT_DEBUG        DynTag = 21 /* Reserved (not used). */
	DT_TEXTREL      DynTag = 22 /* Indicates there may be relocations in non-writable segments. [sup] */
	DT_JMPREL       DynTag = 23 /* Address of PLT relocations. */
	DT_BIND_NOW     DynTag = 24 /* [sup] */
	DT_INIT_ARRAY   DynTag = 25 /* Address of the array of pointers to initialization functions */
	DT_FINI_ARRAY   DynTag = 26 /* Address of the array of pointers to termination functions */
	DT_INIT_ARRAYSZ DynTag = 27 /* Size in bytes of the array of initialization functions. */
	DT_FINI_ARRAYSZ DynTag = 28 /* Size in bytes of the array of termination functions. */
	DT_RUNPATH      DynTag = 29 /* String table offset of a null-terminated library search path string. */
	DT_FLAGS        DynTag = 30 /* Object specific flag values. */
	DT_ENCODING     DynTag = 32 /* Values greater than or equal to DT_ENCODING
	   and less than DT_LOOS follow the rules for
	   the interpretation of the d_un union
	   as follows: even == 'd_ptr', even == 'd_val'
	   or none */
	DT_PREINIT_ARRAY   DynTag = 32 /* Address of the array of pointers to pre-initialization functions. */
	DT_PREINIT_ARRAYSZ DynTag = 33 /* Size in bytes of the array of pre-initialization functions. */
	DT_SYMTAB_SHNDX    DynTag = 34 /* Address of SHT_SYMTAB_SHNDX section. */

	DT_LOOS DynTag = 0x6000000d /* First OS-specific */
	DT_HIOS DynTag = 0x6ffff000 /* Last OS-specific */

	DT_VALRNGLO       DynTag = 0x6ffffd00
	DT_GNU_PRELINKED  DynTag = 0x6ffffdf5
	DT_GNU_CONFLICTSZ DynTag = 0x6ffffdf6
	DT_GNU_LIBLISTSZ  DynTag = 0x6ffffdf7
	DT_CHECKSUM       DynTag = 0x6ffffdf8
	DT_PLTPADSZ       DynTag = 0x6ffffdf9
	DT_MOVEENT        DynTag = 0x6ffffdfa
	DT_MOVESZ         DynTag = 0x6ffffdfb
	DT_FEATURE        DynTag = 0x6ffffdfc
	DT_POSFLAG_1      DynTag = 0x6ffffdfd
	DT_SYMINSZ        DynTag = 0x6ffffdfe
	DT_SYMINENT       DynTag = 0x6ffffdff
	DT_VALRNGHI       DynTag = 0x6ffffdff

	DT_ADDRRNGLO    DynTag = 0x6ffffe00
	DT_GNU_HASH     DynTag = 0x6ffffef5
	DT_TLSDESC_PLT  DynTag = 0x6ffffef6
	DT_TLSDESC_GOT  DynTag = 0x6ffffef7
	DT_GNU_CONFLICT DynTag = 0x6ffffef8
	DT_GNU_LIBLIST  DynTag = 0x6ffffef9
	DT_CONFIG       DynTag = 0x6ffffefa
	DT_DEPAUDIT     DynTag = 0x6ffffefb
	DT_AUDIT        DynTag = 0x6ffffefc
	DT_PLTPAD       DynTag = 0x6ffffefd
	DT_MOVETAB      DynTag = 0x6ffffefe
	DT_SYMINFO      DynTag = 0x6ffffeff
	DT_ADDRRNGHI    DynTag = 0x6ffffeff

	DT_VERSYM     DynTag = 0x6ffffff0
	DT_RELACOUNT  DynTag = 0x6ffffff9
	DT_RELCOUNT   DynTag = 0x6ffffffa
	DT_FLAGS_1    DynTag = 0x6ffffffb
	DT_VERDEF     DynTag = 0x6ffffffc
	DT_VERDEFNUM  DynTag = 0x6ffffffd
	DT_VERNEED    DynTag = 0x6ffffffe
	DT_VERNEEDNUM DynTag = 0x6fffffff

	DT_LOPROC DynTag = 0x70000000 /* First processor-specific type. */

	DT_MIPS_RLD_VERSION           DynTag = 0x70000001
	DT_MIPS_TIME_STAMP            DynTag = 0x70000002
	DT_MIPS_ICHECKSUM             DynTag = 0x70000003
	DT_MIPS_IVERSION              DynTag = 0x70000004
	DT_MIPS_FLAGS                 DynTag = 0x70000005
	DT_MIPS_BASE_ADDRESS          DynTag = 0x70000006
	DT_MIPS_MSYM                  DynTag = 0x70000007
	DT_MIPS_CONFLICT              DynTag = 0x70000008
	DT_MIPS_LIBLIST               DynTag = 0x70000009
	DT_MIPS_LOCAL_GOTNO           DynTag = 0x7000000a
	DT_MIPS_CONFLICTNO            DynTag = 0x7000000b
	DT_MIPS_LIBLISTNO             DynTag = 0x70000010
	DT_MIPS_SYMTABNO              DynTag = 0x70000011
	DT_MIPS_UNREFEXTNO            DynTag = 0x70000012
	DT_MIPS_GOTSYM                DynTag = 0x70000013
	DT_MIPS_HIPAGENO              DynTag = 0x70000014
	DT_MIPS_RLD_MAP               DynTag = 0x70000016
	DT_MIPS_DELTA_CLASS           DynTag = 0x70000017
	DT_MIPS_DELTA_CLASS_NO        DynTag = 0x70000018
	DT_MIPS_DELTA_INSTANCE        DynTag = 0x70000019
	DT_MIPS_DELTA_INSTANCE_NO     DynTag = 0x7000001a
	DT_MIPS_DELTA_RELOC           DynTag = 0x7000001b
	DT_MIPS_DELTA_RELOC_NO        DynTag = 0x7000001c
	DT_MIPS_DELTA_SYM             DynTag = 0x7000001d
	DT_MIPS_DELTA_SYM_NO          DynTag = 0x7000001e
	DT_MIPS_DELTA_CLASSSYM        DynTag = 0x70000020
	DT_MIPS_DELTA_CLASSSYM_NO     DynTag = 0x70000021
	DT_MIPS_CXX_FLAGS             DynTag = 0x70000022
	DT_MIPS_PIXIE_INIT            DynTag = 0x70000023
	DT_MIPS_SYMBOL_LIB            DynTag = 0x70000024
	DT_MIPS_LOCALPAGE_GOTIDX      DynTag = 0x70000025
	DT_MIPS_LOCAL_GOTIDX          DynTag = 0x70000026
	DT_MIPS_HIDDEN_GOTIDX         DynTag = 0x70000027
	DT_MIPS_PROTECTED_GOTIDX      DynTag = 0x70000028
	DT_MIPS_OPTIONS               DynTag = 0x70000029
	DT_MIPS_INTERFACE             DynTag = 0x7000002a
	DT_MIPS_DYNSTR_ALIGN          DynTag = 0x7000002b
	DT_MIPS_INTERFACE_SIZE        DynTag = 0x7000002c
	DT_MIPS_RLD_TEXT_RESOLVE_ADDR DynTag = 0x7000002d
	DT_MIPS_PERF_SUFFIX           DynTag = 0x7000002e
	DT_MIPS_COMPACT_SIZE          DynTag = 0x7000002f
	DT_MIPS_GP_VALUE              DynTag = 0x70000030
	DT_MIPS_AUX_DYNAMIC           DynTag = 0x70000031
	DT_MIPS_PLTGOT                DynTag = 0x70000032
	DT_MIPS_RWPLT                 DynTag = 0x70000034
	DT_MIPS_RLD_MAP_REL           DynTag = 0x70000035

	DT_PPC_GOT DynTag = 0x70000000
	DT_PPC_OPT DynTag = 0x70000001

	DT_PPC64_GLINK DynTag = 0x70000000
	DT_PPC64_OPD   DynTag = 0x70000001
	DT_PPC64_OPDSZ DynTag = 0x70000002
	DT_PPC64_OPT   DynTag = 0x70000003

	DT_SPARC_REGISTER DynTag = 0x70000001

	DT_AUXILIARY DynTag = 0x7ffffffd
	DT_USED      DynTag = 0x7ffffffe
	DT_FILTER    DynTag = 0x7fffffff

	DT_HIPROC DynTag = 0x7fffffff /* Last processor-specific type. */
)

(DynTag) GoString

1
func (i DynTag) GoString() string

(DynTag) String

1
func (i DynTag) String() string

type File

1
2
3
4
5
6
type File struct {
	FileHeader
	Sections []*Section
	Progs    []*Prog
	// contains filtered or unexported fields
}

A File represents an open ELF file.

func NewFile

1
func NewFile(r io.ReaderAt) (*File, error)

NewFile creates a new File for accessing an ELF binary in an underlying reader. The ELF binary is expected to start at position 0 in the ReaderAt.

func Open

1
func Open(name string) (*File, error)

Open opens the named file using os.Open and prepares it for use as an ELF binary.

(*File) Close

1
func (f *File) Close() error

Close closes the File. If the File was created using NewFile directly instead of Open, Close has no effect.

(*File) DWARF

1
func (f *File) DWARF() (*dwarf.Data, error)

(*File) DynString <- go1.1

1
func (f *File) DynString(tag DynTag) ([]string, error)

DynString returns the strings listed for the given tag in the file’s dynamic section.

The tag must be one that takes string values: DT_NEEDED, DT_SONAME, DT_RPATH, or DT_RUNPATH.

(*File) DynamicSymbols <- go1.4

1
func (f *File) DynamicSymbols() ([]Symbol, error)

DynamicSymbols returns the dynamic symbol table for f. The symbols will be listed in the order they appear in f.

If f has a symbol version table, the returned Symbols will have initialized Version and Library fields.

For compatibility with Symbols, DynamicSymbols omits the null symbol at index 0. After retrieving the symbols as symtab, an externally supplied index x corresponds to symtab[x-1], not symtab[x].

(*File) ImportedLibraries

1
func (f *File) ImportedLibraries() ([]string, error)

ImportedLibraries returns the names of all libraries referred to by the binary f that are expected to be linked with the binary at dynamic link time.

(*File) ImportedSymbols

1
func (f *File) ImportedSymbols() ([]ImportedSymbol, error)

ImportedSymbols returns the names of all symbols referred to by the binary f that are expected to be satisfied by other libraries at dynamic load time. It does not return weak symbols.

(*File) Section

1
func (f *File) Section(name string) *Section

Section returns a section with the given name, or nil if no such section exists.

(*File) SectionByType

1
func (f *File) SectionByType(typ SectionType) *Section

SectionByType returns the first section in f with the given type, or nil if there is no such section.

(*File) Symbols

1
func (f *File) Symbols() ([]Symbol, error)

Symbols returns the symbol table for f. The symbols will be listed in the order they appear in f.

For compatibility with Go 1.0, Symbols omits the null symbol at index 0. After retrieving the symbols as symtab, an externally supplied index x corresponds to symtab[x-1], not symtab[x].

type FileHeader

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
type FileHeader struct {
	Class      Class
	Data       Data
	Version    Version
	OSABI      OSABI
	ABIVersion uint8
	ByteOrder  binary.ByteOrder
	Type       Type
	Machine    Machine
	Entry      uint64
}

A FileHeader represents an ELF file header.

type FormatError

1
2
3
type FormatError struct {
	// contains filtered or unexported fields
}

(*FormatError) Error

1
func (e *FormatError) Error() string

type Header32

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
type Header32 struct {
	Ident     [EI_NIDENT]byte /* File identification. */
	Type      uint16          /* File type. */
	Machine   uint16          /* Machine architecture. */
	Version   uint32          /* ELF format version. */
	Entry     uint32          /* Entry point. */
	Phoff     uint32          /* Program header file offset. */
	Shoff     uint32          /* Section header file offset. */
	Flags     uint32          /* Architecture-specific flags. */
	Ehsize    uint16          /* Size of ELF header in bytes. */
	Phentsize uint16          /* Size of program header entry. */
	Phnum     uint16          /* Number of program header entries. */
	Shentsize uint16          /* Size of section header entry. */
	Shnum     uint16          /* Number of section header entries. */
	Shstrndx  uint16          /* Section name strings section. */
}

ELF32 File header.

type Header64

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
type Header64 struct {
	Ident     [EI_NIDENT]byte /* File identification. */
	Type      uint16          /* File type. */
	Machine   uint16          /* Machine architecture. */
	Version   uint32          /* ELF format version. */
	Entry     uint64          /* Entry point. */
	Phoff     uint64          /* Program header file offset. */
	Shoff     uint64          /* Section header file offset. */
	Flags     uint32          /* Architecture-specific flags. */
	Ehsize    uint16          /* Size of ELF header in bytes. */
	Phentsize uint16          /* Size of program header entry. */
	Phnum     uint16          /* Number of program header entries. */
	Shentsize uint16          /* Size of section header entry. */
	Shnum     uint16          /* Number of section header entries. */
	Shstrndx  uint16          /* Section name strings section. */
}

ELF64 file header.

type ImportedSymbol

1
2
3
4
5
type ImportedSymbol struct {
	Name    string
	Version string
	Library string
}

type Machine

1
type Machine uint16

Machine is found in Header.Machine.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
const (
	EM_NONE          Machine = 0   /* Unknown machine. */
	EM_M32           Machine = 1   /* AT&T WE32100. */
	EM_SPARC         Machine = 2   /* Sun SPARC. */
	EM_386           Machine = 3   /* Intel i386. */
	EM_68K           Machine = 4   /* Motorola 68000. */
	EM_88K           Machine = 5   /* Motorola 88000. */
	EM_860           Machine = 7   /* Intel i860. */
	EM_MIPS          Machine = 8   /* MIPS R3000 Big-Endian only. */
	EM_S370          Machine = 9   /* IBM System/370. */
	EM_MIPS_RS3_LE   Machine = 10  /* MIPS R3000 Little-Endian. */
	EM_PARISC        Machine = 15  /* HP PA-RISC. */
	EM_VPP500        Machine = 17  /* Fujitsu VPP500. */
	EM_SPARC32PLUS   Machine = 18  /* SPARC v8plus. */
	EM_960           Machine = 19  /* Intel 80960. */
	EM_PPC           Machine = 20  /* PowerPC 32-bit. */
	EM_PPC64         Machine = 21  /* PowerPC 64-bit. */
	EM_S390          Machine = 22  /* IBM System/390. */
	EM_V800          Machine = 36  /* NEC V800. */
	EM_FR20          Machine = 37  /* Fujitsu FR20. */
	EM_RH32          Machine = 38  /* TRW RH-32. */
	EM_RCE           Machine = 39  /* Motorola RCE. */
	EM_ARM           Machine = 40  /* ARM. */
	EM_SH            Machine = 42  /* Hitachi SH. */
	EM_SPARCV9       Machine = 43  /* SPARC v9 64-bit. */
	EM_TRICORE       Machine = 44  /* Siemens TriCore embedded processor. */
	EM_ARC           Machine = 45  /* Argonaut RISC Core. */
	EM_H8_300        Machine = 46  /* Hitachi H8/300. */
	EM_H8_300H       Machine = 47  /* Hitachi H8/300H. */
	EM_H8S           Machine = 48  /* Hitachi H8S. */
	EM_H8_500        Machine = 49  /* Hitachi H8/500. */
	EM_IA_64         Machine = 50  /* Intel IA-64 Processor. */
	EM_MIPS_X        Machine = 51  /* Stanford MIPS-X. */
	EM_COLDFIRE      Machine = 52  /* Motorola ColdFire. */
	EM_68HC12        Machine = 53  /* Motorola M68HC12. */
	EM_MMA           Machine = 54  /* Fujitsu MMA. */
	EM_PCP           Machine = 55  /* Siemens PCP. */
	EM_NCPU          Machine = 56  /* Sony nCPU. */
	EM_NDR1          Machine = 57  /* Denso NDR1 microprocessor. */
	EM_STARCORE      Machine = 58  /* Motorola Star*Core processor. */
	EM_ME16          Machine = 59  /* Toyota ME16 processor. */
	EM_ST100         Machine = 60  /* STMicroelectronics ST100 processor. */
	EM_TINYJ         Machine = 61  /* Advanced Logic Corp. TinyJ processor. */
	EM_X86_64        Machine = 62  /* Advanced Micro Devices x86-64 */
	EM_PDSP          Machine = 63  /* Sony DSP Processor */
	EM_PDP10         Machine = 64  /* Digital Equipment Corp. PDP-10 */
	EM_PDP11         Machine = 65  /* Digital Equipment Corp. PDP-11 */
	EM_FX66          Machine = 66  /* Siemens FX66 microcontroller */
	EM_ST9PLUS       Machine = 67  /* STMicroelectronics ST9+ 8/16 bit microcontroller */
	EM_ST7           Machine = 68  /* STMicroelectronics ST7 8-bit microcontroller */
	EM_68HC16        Machine = 69  /* Motorola MC68HC16 Microcontroller */
	EM_68HC11        Machine = 70  /* Motorola MC68HC11 Microcontroller */
	EM_68HC08        Machine = 71  /* Motorola MC68HC08 Microcontroller */
	EM_68HC05        Machine = 72  /* Motorola MC68HC05 Microcontroller */
	EM_SVX           Machine = 73  /* Silicon Graphics SVx */
	EM_ST19          Machine = 74  /* STMicroelectronics ST19 8-bit microcontroller */
	EM_VAX           Machine = 75  /* Digital VAX */
	EM_CRIS          Machine = 76  /* Axis Communications 32-bit embedded processor */
	EM_JAVELIN       Machine = 77  /* Infineon Technologies 32-bit embedded processor */
	EM_FIREPATH      Machine = 78  /* Element 14 64-bit DSP Processor */
	EM_ZSP           Machine = 79  /* LSI Logic 16-bit DSP Processor */
	EM_MMIX          Machine = 80  /* Donald Knuth's educational 64-bit processor */
	EM_HUANY         Machine = 81  /* Harvard University machine-independent object files */
	EM_PRISM         Machine = 82  /* SiTera Prism */
	EM_AVR           Machine = 83  /* Atmel AVR 8-bit microcontroller */
	EM_FR30          Machine = 84  /* Fujitsu FR30 */
	EM_D10V          Machine = 85  /* Mitsubishi D10V */
	EM_D30V          Machine = 86  /* Mitsubishi D30V */
	EM_V850          Machine = 87  /* NEC v850 */
	EM_M32R          Machine = 88  /* Mitsubishi M32R */
	EM_MN10300       Machine = 89  /* Matsushita MN10300 */
	EM_MN10200       Machine = 90  /* Matsushita MN10200 */
	EM_PJ            Machine = 91  /* picoJava */
	EM_OPENRISC      Machine = 92  /* OpenRISC 32-bit embedded processor */
	EM_ARC_COMPACT   Machine = 93  /* ARC International ARCompact processor (old spelling/synonym: EM_ARC_A5) */
	EM_XTENSA        Machine = 94  /* Tensilica Xtensa Architecture */
	EM_VIDEOCORE     Machine = 95  /* Alphamosaic VideoCore processor */
	EM_TMM_GPP       Machine = 96  /* Thompson Multimedia General Purpose Processor */
	EM_NS32K         Machine = 97  /* National Semiconductor 32000 series */
	EM_TPC           Machine = 98  /* Tenor Network TPC processor */
	EM_SNP1K         Machine = 99  /* Trebia SNP 1000 processor */
	EM_ST200         Machine = 100 /* STMicroelectronics (www.st.com) ST200 microcontroller */
	EM_IP2K          Machine = 101 /* Ubicom IP2xxx microcontroller family */
	EM_MAX           Machine = 102 /* MAX Processor */
	EM_CR            Machine = 103 /* National Semiconductor CompactRISC microprocessor */
	EM_F2MC16        Machine = 104 /* Fujitsu F2MC16 */
	EM_MSP430        Machine = 105 /* Texas Instruments embedded microcontroller msp430 */
	EM_BLACKFIN      Machine = 106 /* Analog Devices Blackfin (DSP) processor */
	EM_SE_C33        Machine = 107 /* S1C33 Family of Seiko Epson processors */
	EM_SEP           Machine = 108 /* Sharp embedded microprocessor */
	EM_ARCA          Machine = 109 /* Arca RISC Microprocessor */
	EM_UNICORE       Machine = 110 /* Microprocessor series from PKU-Unity Ltd. and MPRC of Peking University */
	EM_EXCESS        Machine = 111 /* eXcess: 16/32/64-bit configurable embedded CPU */
	EM_DXP           Machine = 112 /* Icera Semiconductor Inc. Deep Execution Processor */
	EM_ALTERA_NIOS2  Machine = 113 /* Altera Nios II soft-core processor */
	EM_CRX           Machine = 114 /* National Semiconductor CompactRISC CRX microprocessor */
	EM_XGATE         Machine = 115 /* Motorola XGATE embedded processor */
	EM_C166          Machine = 116 /* Infineon C16x/XC16x processor */
	EM_M16C          Machine = 117 /* Renesas M16C series microprocessors */
	EM_DSPIC30F      Machine = 118 /* Microchip Technology dsPIC30F Digital Signal Controller */
	EM_CE            Machine = 119 /* Freescale Communication Engine RISC core */
	EM_M32C          Machine = 120 /* Renesas M32C series microprocessors */
	EM_TSK3000       Machine = 131 /* Altium TSK3000 core */
	EM_RS08          Machine = 132 /* Freescale RS08 embedded processor */
	EM_SHARC         Machine = 133 /* Analog Devices SHARC family of 32-bit DSP processors */
	EM_ECOG2         Machine = 134 /* Cyan Technology eCOG2 microprocessor */
	EM_SCORE7        Machine = 135 /* Sunplus S+core7 RISC processor */
	EM_DSP24         Machine = 136 /* New Japan Radio (NJR) 24-bit DSP Processor */
	EM_VIDEOCORE3    Machine = 137 /* Broadcom VideoCore III processor */
	EM_LATTICEMICO32 Machine = 138 /* RISC processor for Lattice FPGA architecture */
	EM_SE_C17        Machine = 139 /* Seiko Epson C17 family */
	EM_TI_C6000      Machine = 140 /* The Texas Instruments TMS320C6000 DSP family */
	EM_TI_C2000      Machine = 141 /* The Texas Instruments TMS320C2000 DSP family */
	EM_TI_C5500      Machine = 142 /* The Texas Instruments TMS320C55x DSP family */
	EM_TI_ARP32      Machine = 143 /* Texas Instruments Application Specific RISC Processor, 32bit fetch */
	EM_TI_PRU        Machine = 144 /* Texas Instruments Programmable Realtime Unit */
	EM_MMDSP_PLUS    Machine = 160 /* STMicroelectronics 64bit VLIW Data Signal Processor */
	EM_CYPRESS_M8C   Machine = 161 /* Cypress M8C microprocessor */
	EM_R32C          Machine = 162 /* Renesas R32C series microprocessors */
	EM_TRIMEDIA      Machine = 163 /* NXP Semiconductors TriMedia architecture family */
	EM_QDSP6         Machine = 164 /* QUALCOMM DSP6 Processor */
	EM_8051          Machine = 165 /* Intel 8051 and variants */
	EM_STXP7X        Machine = 166 /* STMicroelectronics STxP7x family of configurable and extensible RISC processors */
	EM_NDS32         Machine = 167 /* Andes Technology compact code size embedded RISC processor family */
	EM_ECOG1         Machine = 168 /* Cyan Technology eCOG1X family */
	EM_ECOG1X        Machine = 168 /* Cyan Technology eCOG1X family */
	EM_MAXQ30        Machine = 169 /* Dallas Semiconductor MAXQ30 Core Micro-controllers */
	EM_XIMO16        Machine = 170 /* New Japan Radio (NJR) 16-bit DSP Processor */
	EM_MANIK         Machine = 171 /* M2000 Reconfigurable RISC Microprocessor */
	EM_CRAYNV2       Machine = 172 /* Cray Inc. NV2 vector architecture */
	EM_RX            Machine = 173 /* Renesas RX family */
	EM_METAG         Machine = 174 /* Imagination Technologies META processor architecture */
	EM_MCST_ELBRUS   Machine = 175 /* MCST Elbrus general purpose hardware architecture */
	EM_ECOG16        Machine = 176 /* Cyan Technology eCOG16 family */
	EM_CR16          Machine = 177 /* National Semiconductor CompactRISC CR16 16-bit microprocessor */
	EM_ETPU          Machine = 178 /* Freescale Extended Time Processing Unit */
	EM_SLE9X         Machine = 179 /* Infineon Technologies SLE9X core */
	EM_L10M          Machine = 180 /* Intel L10M */
	EM_K10M          Machine = 181 /* Intel K10M */
	EM_AARCH64       Machine = 183 /* ARM 64-bit Architecture (AArch64) */
	EM_AVR32         Machine = 185 /* Atmel Corporation 32-bit microprocessor family */
	EM_STM8          Machine = 186 /* STMicroeletronics STM8 8-bit microcontroller */
	EM_TILE64        Machine = 187 /* Tilera TILE64 multicore architecture family */
	EM_TILEPRO       Machine = 188 /* Tilera TILEPro multicore architecture family */
	EM_MICROBLAZE    Machine = 189 /* Xilinx MicroBlaze 32-bit RISC soft processor core */
	EM_CUDA          Machine = 190 /* NVIDIA CUDA architecture */
	EM_TILEGX        Machine = 191 /* Tilera TILE-Gx multicore architecture family */
	EM_CLOUDSHIELD   Machine = 192 /* CloudShield architecture family */
	EM_COREA_1ST     Machine = 193 /* KIPO-KAIST Core-A 1st generation processor family */
	EM_COREA_2ND     Machine = 194 /* KIPO-KAIST Core-A 2nd generation processor family */
	EM_ARC_COMPACT2  Machine = 195 /* Synopsys ARCompact V2 */
	EM_OPEN8         Machine = 196 /* Open8 8-bit RISC soft processor core */
	EM_RL78          Machine = 197 /* Renesas RL78 family */
	EM_VIDEOCORE5    Machine = 198 /* Broadcom VideoCore V processor */
	EM_78KOR         Machine = 199 /* Renesas 78KOR family */
	EM_56800EX       Machine = 200 /* Freescale 56800EX Digital Signal Controller (DSC) */
	EM_BA1           Machine = 201 /* Beyond BA1 CPU architecture */
	EM_BA2           Machine = 202 /* Beyond BA2 CPU architecture */
	EM_XCORE         Machine = 203 /* XMOS xCORE processor family */
	EM_MCHP_PIC      Machine = 204 /* Microchip 8-bit PIC(r) family */
	EM_INTEL205      Machine = 205 /* Reserved by Intel */
	EM_INTEL206      Machine = 206 /* Reserved by Intel */
	EM_INTEL207      Machine = 207 /* Reserved by Intel */
	EM_INTEL208      Machine = 208 /* Reserved by Intel */
	EM_INTEL209      Machine = 209 /* Reserved by Intel */
	EM_KM32          Machine = 210 /* KM211 KM32 32-bit processor */
	EM_KMX32         Machine = 211 /* KM211 KMX32 32-bit processor */
	EM_KMX16         Machine = 212 /* KM211 KMX16 16-bit processor */
	EM_KMX8          Machine = 213 /* KM211 KMX8 8-bit processor */
	EM_KVARC         Machine = 214 /* KM211 KVARC processor */
	EM_CDP           Machine = 215 /* Paneve CDP architecture family */
	EM_COGE          Machine = 216 /* Cognitive Smart Memory Processor */
	EM_COOL          Machine = 217 /* Bluechip Systems CoolEngine */
	EM_NORC          Machine = 218 /* Nanoradio Optimized RISC */
	EM_CSR_KALIMBA   Machine = 219 /* CSR Kalimba architecture family */
	EM_Z80           Machine = 220 /* Zilog Z80 */
	EM_VISIUM        Machine = 221 /* Controls and Data Services VISIUMcore processor */
	EM_FT32          Machine = 222 /* FTDI Chip FT32 high performance 32-bit RISC architecture */
	EM_MOXIE         Machine = 223 /* Moxie processor family */
	EM_AMDGPU        Machine = 224 /* AMD GPU architecture */
	EM_RISCV         Machine = 243 /* RISC-V */
	EM_LANAI         Machine = 244 /* Lanai 32-bit processor */
	EM_BPF           Machine = 247 /* Linux BPF – in-kernel virtual machine */
	EM_LOONGARCH     Machine = 258 /* LoongArch */

	/* Non-standard or deprecated. */
	EM_486         Machine = 6      /* Intel i486. */
	EM_MIPS_RS4_BE Machine = 10     /* MIPS R4000 Big-Endian */
	EM_ALPHA_STD   Machine = 41     /* Digital Alpha (standard value). */
	EM_ALPHA       Machine = 0x9026 /* Alpha (written in the absence of an ABI) */
)

(Machine) GoString

1
func (i Machine) GoString() string

(Machine) String

1
func (i Machine) String() string

type NType

1
type NType int

NType values; used in core files.

1
2
3
4
5
const (
	NT_PRSTATUS NType = 1 /* Process status. */
	NT_FPREGSET NType = 2 /* Floating point registers. */
	NT_PRPSINFO NType = 3 /* Process state info. */
)

(NType) GoString

1
func (i NType) GoString() string

(NType) String

1
func (i NType) String() string

type OSABI

1
type OSABI byte

OSABI is found in Header.Ident[EI_OSABI] and Header.OSABI.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
const (
	ELFOSABI_NONE       OSABI = 0   /* UNIX System V ABI */
	ELFOSABI_HPUX       OSABI = 1   /* HP-UX operating system */
	ELFOSABI_NETBSD     OSABI = 2   /* NetBSD */
	ELFOSABI_LINUX      OSABI = 3   /* Linux */
	ELFOSABI_HURD       OSABI = 4   /* Hurd */
	ELFOSABI_86OPEN     OSABI = 5   /* 86Open common IA32 ABI */
	ELFOSABI_SOLARIS    OSABI = 6   /* Solaris */
	ELFOSABI_AIX        OSABI = 7   /* AIX */
	ELFOSABI_IRIX       OSABI = 8   /* IRIX */
	ELFOSABI_FREEBSD    OSABI = 9   /* FreeBSD */
	ELFOSABI_TRU64      OSABI = 10  /* TRU64 UNIX */
	ELFOSABI_MODESTO    OSABI = 11  /* Novell Modesto */
	ELFOSABI_OPENBSD    OSABI = 12  /* OpenBSD */
	ELFOSABI_OPENVMS    OSABI = 13  /* Open VMS */
	ELFOSABI_NSK        OSABI = 14  /* HP Non-Stop Kernel */
	ELFOSABI_AROS       OSABI = 15  /* Amiga Research OS */
	ELFOSABI_FENIXOS    OSABI = 16  /* The FenixOS highly scalable multi-core OS */
	ELFOSABI_CLOUDABI   OSABI = 17  /* Nuxi CloudABI */
	ELFOSABI_ARM        OSABI = 97  /* ARM */
	ELFOSABI_STANDALONE OSABI = 255 /* Standalone (embedded) application */
)

(OSABI) GoString

1
func (i OSABI) GoString() string

(OSABI) String

1
func (i OSABI) String() string

type Prog

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
type Prog struct {
	ProgHeader

	// Embed ReaderAt for ReadAt method.
	// Do not embed SectionReader directly
	// to avoid having Read and Seek.
	// If a client wants Read and Seek it must use
	// Open() to avoid fighting over the seek offset
	// with other clients.
	io.ReaderAt
	// contains filtered or unexported fields
}

A Prog represents a single ELF program header in an ELF binary.

(*Prog) Open

1
func (p *Prog) Open() io.ReadSeeker

Open returns a new ReadSeeker reading the ELF program body.

type Prog32

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
type Prog32 struct {
	Type   uint32 /* Entry type. */
	Off    uint32 /* File offset of contents. */
	Vaddr  uint32 /* Virtual address in memory image. */
	Paddr  uint32 /* Physical address (not used). */
	Filesz uint32 /* Size of contents in file. */
	Memsz  uint32 /* Size of contents in memory. */
	Flags  uint32 /* Access permission flags. */
	Align  uint32 /* Alignment in memory and file. */
}

ELF32 Program header.

type Prog64

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
type Prog64 struct {
	Type   uint32 /* Entry type. */
	Flags  uint32 /* Access permission flags. */
	Off    uint64 /* File offset of contents. */
	Vaddr  uint64 /* Virtual address in memory image. */
	Paddr  uint64 /* Physical address (not used). */
	Filesz uint64 /* Size of contents in file. */
	Memsz  uint64 /* Size of contents in memory. */
	Align  uint64 /* Alignment in memory and file. */
}

ELF64 Program header.

type ProgFlag

1
type ProgFlag uint32

Prog.Flag

1
2
3
4
5
6
7
const (
	PF_X        ProgFlag = 0x1        /* Executable. */
	PF_W        ProgFlag = 0x2        /* Writable. */
	PF_R        ProgFlag = 0x4        /* Readable. */
	PF_MASKOS   ProgFlag = 0x0ff00000 /* Operating system-specific. */
	PF_MASKPROC ProgFlag = 0xf0000000 /* Processor-specific. */
)

(ProgFlag) GoString

1
func (i ProgFlag) GoString() string

(ProgFlag) String

1
func (i ProgFlag) String() string

type ProgHeader

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
type ProgHeader struct {
	Type   ProgType
	Flags  ProgFlag
	Off    uint64
	Vaddr  uint64
	Paddr  uint64
	Filesz uint64
	Memsz  uint64
	Align  uint64
}

A ProgHeader represents a single ELF program header.

type ProgType

1
type ProgType int

Prog.Type

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
const (
	PT_NULL    ProgType = 0 /* Unused entry. */
	PT_LOAD    ProgType = 1 /* Loadable segment. */
	PT_DYNAMIC ProgType = 2 /* Dynamic linking information segment. */
	PT_INTERP  ProgType = 3 /* Pathname of interpreter. */
	PT_NOTE    ProgType = 4 /* Auxiliary information. */
	PT_SHLIB   ProgType = 5 /* Reserved (not used). */
	PT_PHDR    ProgType = 6 /* Location of program header itself. */
	PT_TLS     ProgType = 7 /* Thread local storage segment */

	PT_LOOS ProgType = 0x60000000 /* First OS-specific. */

	PT_GNU_EH_FRAME ProgType = 0x6474e550 /* Frame unwind information */
	PT_GNU_STACK    ProgType = 0x6474e551 /* Stack flags */
	PT_GNU_RELRO    ProgType = 0x6474e552 /* Read only after relocs */
	PT_GNU_PROPERTY ProgType = 0x6474e553 /* GNU property */
	PT_GNU_MBIND_LO ProgType = 0x6474e555 /* Mbind segments start */
	PT_GNU_MBIND_HI ProgType = 0x6474f554 /* Mbind segments finish */

	PT_PAX_FLAGS ProgType = 0x65041580 /* PAX flags */

	PT_OPENBSD_RANDOMIZE ProgType = 0x65a3dbe6 /* Random data */
	PT_OPENBSD_WXNEEDED  ProgType = 0x65a3dbe7 /* W^X violations */
	PT_OPENBSD_BOOTDATA  ProgType = 0x65a41be6 /* Boot arguments */

	PT_SUNW_EH_FRAME ProgType = 0x6474e550 /* Frame unwind information */
	PT_SUNWSTACK     ProgType = 0x6ffffffb /* Stack segment */

	PT_HIOS ProgType = 0x6fffffff /* Last OS-specific. */

	PT_LOPROC ProgType = 0x70000000 /* First processor-specific type. */

	PT_ARM_ARCHEXT ProgType = 0x70000000 /* Architecture compatibility */
	PT_ARM_EXIDX   ProgType = 0x70000001 /* Exception unwind tables */

	PT_AARCH64_ARCHEXT ProgType = 0x70000000 /* Architecture compatibility */
	PT_AARCH64_UNWIND  ProgType = 0x70000001 /* Exception unwind tables */

	PT_MIPS_REGINFO  ProgType = 0x70000000 /* Register usage */
	PT_MIPS_RTPROC   ProgType = 0x70000001 /* Runtime procedures */
	PT_MIPS_OPTIONS  ProgType = 0x70000002 /* Options */
	PT_MIPS_ABIFLAGS ProgType = 0x70000003 /* ABI flags */

	PT_S390_PGSTE ProgType = 0x70000000 /* 4k page table size */

	PT_HIPROC ProgType = 0x7fffffff /* Last processor-specific type. */
)

(ProgType) GoString

1
func (i ProgType) GoString() string

(ProgType) String

1
func (i ProgType) String() string

type R_386

1
type R_386 int

Relocation types for 386.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
const (
	R_386_NONE          R_386 = 0  /* No relocation. */
	R_386_32            R_386 = 1  /* Add symbol value. */
	R_386_PC32          R_386 = 2  /* Add PC-relative symbol value. */
	R_386_GOT32         R_386 = 3  /* Add PC-relative GOT offset. */
	R_386_PLT32         R_386 = 4  /* Add PC-relative PLT offset. */
	R_386_COPY          R_386 = 5  /* Copy data from shared object. */
	R_386_GLOB_DAT      R_386 = 6  /* Set GOT entry to data address. */
	R_386_JMP_SLOT      R_386 = 7  /* Set GOT entry to code address. */
	R_386_RELATIVE      R_386 = 8  /* Add load address of shared object. */
	R_386_GOTOFF        R_386 = 9  /* Add GOT-relative symbol address. */
	R_386_GOTPC         R_386 = 10 /* Add PC-relative GOT table address. */
	R_386_32PLT         R_386 = 11
	R_386_TLS_TPOFF     R_386 = 14 /* Negative offset in static TLS block */
	R_386_TLS_IE        R_386 = 15 /* Absolute address of GOT for -ve static TLS */
	R_386_TLS_GOTIE     R_386 = 16 /* GOT entry for negative static TLS block */
	R_386_TLS_LE        R_386 = 17 /* Negative offset relative to static TLS */
	R_386_TLS_GD        R_386 = 18 /* 32 bit offset to GOT (index,off) pair */
	R_386_TLS_LDM       R_386 = 19 /* 32 bit offset to GOT (index,zero) pair */
	R_386_16            R_386 = 20
	R_386_PC16          R_386 = 21
	R_386_8             R_386 = 22
	R_386_PC8           R_386 = 23
	R_386_TLS_GD_32     R_386 = 24 /* 32 bit offset to GOT (index,off) pair */
	R_386_TLS_GD_PUSH   R_386 = 25 /* pushl instruction for Sun ABI GD sequence */
	R_386_TLS_GD_CALL   R_386 = 26 /* call instruction for Sun ABI GD sequence */
	R_386_TLS_GD_POP    R_386 = 27 /* popl instruction for Sun ABI GD sequence */
	R_386_TLS_LDM_32    R_386 = 28 /* 32 bit offset to GOT (index,zero) pair */
	R_386_TLS_LDM_PUSH  R_386 = 29 /* pushl instruction for Sun ABI LD sequence */
	R_386_TLS_LDM_CALL  R_386 = 30 /* call instruction for Sun ABI LD sequence */
	R_386_TLS_LDM_POP   R_386 = 31 /* popl instruction for Sun ABI LD sequence */
	R_386_TLS_LDO_32    R_386 = 32 /* 32 bit offset from start of TLS block */
	R_386_TLS_IE_32     R_386 = 33 /* 32 bit offset to GOT static TLS offset entry */
	R_386_TLS_LE_32     R_386 = 34 /* 32 bit offset within static TLS block */
	R_386_TLS_DTPMOD32  R_386 = 35 /* GOT entry containing TLS index */
	R_386_TLS_DTPOFF32  R_386 = 36 /* GOT entry containing TLS offset */
	R_386_TLS_TPOFF32   R_386 = 37 /* GOT entry of -ve static TLS offset */
	R_386_SIZE32        R_386 = 38
	R_386_TLS_GOTDESC   R_386 = 39
	R_386_TLS_DESC_CALL R_386 = 40
	R_386_TLS_DESC      R_386 = 41
	R_386_IRELATIVE     R_386 = 42
	R_386_GOT32X        R_386 = 43
)

(R_386) GoString

1
func (i R_386) GoString() string

(R_386) String

1
func (i R_386) String() string

type R_390 <- go1.7

1
type R_390 int

Relocation types for s390x processors.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
const (
	R_390_NONE        R_390 = 0
	R_390_8           R_390 = 1
	R_390_12          R_390 = 2
	R_390_16          R_390 = 3
	R_390_32          R_390 = 4
	R_390_PC32        R_390 = 5
	R_390_GOT12       R_390 = 6
	R_390_GOT32       R_390 = 7
	R_390_PLT32       R_390 = 8
	R_390_COPY        R_390 = 9
	R_390_GLOB_DAT    R_390 = 10
	R_390_JMP_SLOT    R_390 = 11
	R_390_RELATIVE    R_390 = 12
	R_390_GOTOFF      R_390 = 13
	R_390_GOTPC       R_390 = 14
	R_390_GOT16       R_390 = 15
	R_390_PC16        R_390 = 16
	R_390_PC16DBL     R_390 = 17
	R_390_PLT16DBL    R_390 = 18
	R_390_PC32DBL     R_390 = 19
	R_390_PLT32DBL    R_390 = 20
	R_390_GOTPCDBL    R_390 = 21
	R_390_64          R_390 = 22
	R_390_PC64        R_390 = 23
	R_390_GOT64       R_390 = 24
	R_390_PLT64       R_390 = 25
	R_390_GOTENT      R_390 = 26
	R_390_GOTOFF16    R_390 = 27
	R_390_GOTOFF64    R_390 = 28
	R_390_GOTPLT12    R_390 = 29
	R_390_GOTPLT16    R_390 = 30
	R_390_GOTPLT32    R_390 = 31
	R_390_GOTPLT64    R_390 = 32
	R_390_GOTPLTENT   R_390 = 33
	R_390_GOTPLTOFF16 R_390 = 34
	R_390_GOTPLTOFF32 R_390 = 35
	R_390_GOTPLTOFF64 R_390 = 36
	R_390_TLS_LOAD    R_390 = 37
	R_390_TLS_GDCALL  R_390 = 38
	R_390_TLS_LDCALL  R_390 = 39
	R_390_TLS_GD32    R_390 = 40
	R_390_TLS_GD64    R_390 = 41
	R_390_TLS_GOTIE12 R_390 = 42
	R_390_TLS_GOTIE32 R_390 = 43
	R_390_TLS_GOTIE64 R_390 = 44
	R_390_TLS_LDM32   R_390 = 45
	R_390_TLS_LDM64   R_390 = 46
	R_390_TLS_IE32    R_390 = 47
	R_390_TLS_IE64    R_390 = 48
	R_390_TLS_IEENT   R_390 = 49
	R_390_TLS_LE32    R_390 = 50
	R_390_TLS_LE64    R_390 = 51
	R_390_TLS_LDO32   R_390 = 52
	R_390_TLS_LDO64   R_390 = 53
	R_390_TLS_DTPMOD  R_390 = 54
	R_390_TLS_DTPOFF  R_390 = 55
	R_390_TLS_TPOFF   R_390 = 56
	R_390_20          R_390 = 57
	R_390_GOT20       R_390 = 58
	R_390_GOTPLT20    R_390 = 59
	R_390_TLS_GOTIE20 R_390 = 60
)

(R_390) GoString <- go1.7

1
func (i R_390) GoString() string

(R_390) String <- go1.7

1
func (i R_390) String() string

type R_AARCH64 <- go1.4

1
type R_AARCH64 int

Relocation types for AArch64 (aka arm64)

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
const (
	R_AARCH64_NONE                            R_AARCH64 = 0
	R_AARCH64_P32_ABS32                       R_AARCH64 = 1
	R_AARCH64_P32_ABS16                       R_AARCH64 = 2
	R_AARCH64_P32_PREL32                      R_AARCH64 = 3
	R_AARCH64_P32_PREL16                      R_AARCH64 = 4
	R_AARCH64_P32_MOVW_UABS_G0                R_AARCH64 = 5
	R_AARCH64_P32_MOVW_UABS_G0_NC             R_AARCH64 = 6
	R_AARCH64_P32_MOVW_UABS_G1                R_AARCH64 = 7
	R_AARCH64_P32_MOVW_SABS_G0                R_AARCH64 = 8
	R_AARCH64_P32_LD_PREL_LO19                R_AARCH64 = 9
	R_AARCH64_P32_ADR_PREL_LO21               R_AARCH64 = 10
	R_AARCH64_P32_ADR_PREL_PG_HI21            R_AARCH64 = 11
	R_AARCH64_P32_ADD_ABS_LO12_NC             R_AARCH64 = 12
	R_AARCH64_P32_LDST8_ABS_LO12_NC           R_AARCH64 = 13
	R_AARCH64_P32_LDST16_ABS_LO12_NC          R_AARCH64 = 14
	R_AARCH64_P32_LDST32_ABS_LO12_NC          R_AARCH64 = 15
	R_AARCH64_P32_LDST64_ABS_LO12_NC          R_AARCH64 = 16
	R_AARCH64_P32_LDST128_ABS_LO12_NC         R_AARCH64 = 17
	R_AARCH64_P32_TSTBR14                     R_AARCH64 = 18
	R_AARCH64_P32_CONDBR19                    R_AARCH64 = 19
	R_AARCH64_P32_JUMP26                      R_AARCH64 = 20
	R_AARCH64_P32_CALL26                      R_AARCH64 = 21
	R_AARCH64_P32_GOT_LD_PREL19               R_AARCH64 = 25
	R_AARCH64_P32_ADR_GOT_PAGE                R_AARCH64 = 26
	R_AARCH64_P32_LD32_GOT_LO12_NC            R_AARCH64 = 27
	R_AARCH64_P32_TLSGD_ADR_PAGE21            R_AARCH64 = 81
	R_AARCH64_P32_TLSGD_ADD_LO12_NC           R_AARCH64 = 82
	R_AARCH64_P32_TLSIE_ADR_GOTTPREL_PAGE21   R_AARCH64 = 103
	R_AARCH64_P32_TLSIE_LD32_GOTTPREL_LO12_NC R_AARCH64 = 104
	R_AARCH64_P32_TLSIE_LD_GOTTPREL_PREL19    R_AARCH64 = 105
	R_AARCH64_P32_TLSLE_MOVW_TPREL_G1         R_AARCH64 = 106
	R_AARCH64_P32_TLSLE_MOVW_TPREL_G0         R_AARCH64 = 107
	R_AARCH64_P32_TLSLE_MOVW_TPREL_G0_NC      R_AARCH64 = 108
	R_AARCH64_P32_TLSLE_ADD_TPREL_HI12        R_AARCH64 = 109
	R_AARCH64_P32_TLSLE_ADD_TPREL_LO12        R_AARCH64 = 110
	R_AARCH64_P32_TLSLE_ADD_TPREL_LO12_NC     R_AARCH64 = 111
	R_AARCH64_P32_TLSDESC_LD_PREL19           R_AARCH64 = 122
	R_AARCH64_P32_TLSDESC_ADR_PREL21          R_AARCH64 = 123
	R_AARCH64_P32_TLSDESC_ADR_PAGE21          R_AARCH64 = 124
	R_AARCH64_P32_TLSDESC_LD32_LO12_NC        R_AARCH64 = 125
	R_AARCH64_P32_TLSDESC_ADD_LO12_NC         R_AARCH64 = 126
	R_AARCH64_P32_TLSDESC_CALL                R_AARCH64 = 127
	R_AARCH64_P32_COPY                        R_AARCH64 = 180
	R_AARCH64_P32_GLOB_DAT                    R_AARCH64 = 181
	R_AARCH64_P32_JUMP_SLOT                   R_AARCH64 = 182
	R_AARCH64_P32_RELATIVE                    R_AARCH64 = 183
	R_AARCH64_P32_TLS_DTPMOD                  R_AARCH64 = 184
	R_AARCH64_P32_TLS_DTPREL                  R_AARCH64 = 185
	R_AARCH64_P32_TLS_TPREL                   R_AARCH64 = 186
	R_AARCH64_P32_TLSDESC                     R_AARCH64 = 187
	R_AARCH64_P32_IRELATIVE                   R_AARCH64 = 188
	R_AARCH64_NULL                            R_AARCH64 = 256
	R_AARCH64_ABS64                           R_AARCH64 = 257
	R_AARCH64_ABS32                           R_AARCH64 = 258
	R_AARCH64_ABS16                           R_AARCH64 = 259
	R_AARCH64_PREL64                          R_AARCH64 = 260
	R_AARCH64_PREL32                          R_AARCH64 = 261
	R_AARCH64_PREL16                          R_AARCH64 = 262
	R_AARCH64_MOVW_UABS_G0                    R_AARCH64 = 263
	R_AARCH64_MOVW_UABS_G0_NC                 R_AARCH64 = 264
	R_AARCH64_MOVW_UABS_G1                    R_AARCH64 = 265
	R_AARCH64_MOVW_UABS_G1_NC                 R_AARCH64 = 266
	R_AARCH64_MOVW_UABS_G2                    R_AARCH64 = 267
	R_AARCH64_MOVW_UABS_G2_NC                 R_AARCH64 = 268
	R_AARCH64_MOVW_UABS_G3                    R_AARCH64 = 269
	R_AARCH64_MOVW_SABS_G0                    R_AARCH64 = 270
	R_AARCH64_MOVW_SABS_G1                    R_AARCH64 = 271
	R_AARCH64_MOVW_SABS_G2                    R_AARCH64 = 272
	R_AARCH64_LD_PREL_LO19                    R_AARCH64 = 273
	R_AARCH64_ADR_PREL_LO21                   R_AARCH64 = 274
	R_AARCH64_ADR_PREL_PG_HI21                R_AARCH64 = 275
	R_AARCH64_ADR_PREL_PG_HI21_NC             R_AARCH64 = 276
	R_AARCH64_ADD_ABS_LO12_NC                 R_AARCH64 = 277
	R_AARCH64_LDST8_ABS_LO12_NC               R_AARCH64 = 278
	R_AARCH64_TSTBR14                         R_AARCH64 = 279
	R_AARCH64_CONDBR19                        R_AARCH64 = 280
	R_AARCH64_JUMP26                          R_AARCH64 = 282
	R_AARCH64_CALL26                          R_AARCH64 = 283
	R_AARCH64_LDST16_ABS_LO12_NC              R_AARCH64 = 284
	R_AARCH64_LDST32_ABS_LO12_NC              R_AARCH64 = 285
	R_AARCH64_LDST64_ABS_LO12_NC              R_AARCH64 = 286
	R_AARCH64_LDST128_ABS_LO12_NC             R_AARCH64 = 299
	R_AARCH64_GOT_LD_PREL19                   R_AARCH64 = 309
	R_AARCH64_LD64_GOTOFF_LO15                R_AARCH64 = 310
	R_AARCH64_ADR_GOT_PAGE                    R_AARCH64 = 311
	R_AARCH64_LD64_GOT_LO12_NC                R_AARCH64 = 312
	R_AARCH64_LD64_GOTPAGE_LO15               R_AARCH64 = 313
	R_AARCH64_TLSGD_ADR_PREL21                R_AARCH64 = 512
	R_AARCH64_TLSGD_ADR_PAGE21                R_AARCH64 = 513
	R_AARCH64_TLSGD_ADD_LO12_NC               R_AARCH64 = 514
	R_AARCH64_TLSGD_MOVW_G1                   R_AARCH64 = 515
	R_AARCH64_TLSGD_MOVW_G0_NC                R_AARCH64 = 516
	R_AARCH64_TLSLD_ADR_PREL21                R_AARCH64 = 517
	R_AARCH64_TLSLD_ADR_PAGE21                R_AARCH64 = 518
	R_AARCH64_TLSIE_MOVW_GOTTPREL_G1          R_AARCH64 = 539
	R_AARCH64_TLSIE_MOVW_GOTTPREL_G0_NC       R_AARCH64 = 540
	R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21       R_AARCH64 = 541
	R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC     R_AARCH64 = 542
	R_AARCH64_TLSIE_LD_GOTTPREL_PREL19        R_AARCH64 = 543
	R_AARCH64_TLSLE_MOVW_TPREL_G2             R_AARCH64 = 544
	R_AARCH64_TLSLE_MOVW_TPREL_G1             R_AARCH64 = 545
	R_AARCH64_TLSLE_MOVW_TPREL_G1_NC          R_AARCH64 = 546
	R_AARCH64_TLSLE_MOVW_TPREL_G0             R_AARCH64 = 547
	R_AARCH64_TLSLE_MOVW_TPREL_G0_NC          R_AARCH64 = 548
	R_AARCH64_TLSLE_ADD_TPREL_HI12            R_AARCH64 = 549
	R_AARCH64_TLSLE_ADD_TPREL_LO12            R_AARCH64 = 550
	R_AARCH64_TLSLE_ADD_TPREL_LO12_NC         R_AARCH64 = 551
	R_AARCH64_TLSDESC_LD_PREL19               R_AARCH64 = 560
	R_AARCH64_TLSDESC_ADR_PREL21              R_AARCH64 = 561
	R_AARCH64_TLSDESC_ADR_PAGE21              R_AARCH64 = 562
	R_AARCH64_TLSDESC_LD64_LO12_NC            R_AARCH64 = 563
	R_AARCH64_TLSDESC_ADD_LO12_NC             R_AARCH64 = 564
	R_AARCH64_TLSDESC_OFF_G1                  R_AARCH64 = 565
	R_AARCH64_TLSDESC_OFF_G0_NC               R_AARCH64 = 566
	R_AARCH64_TLSDESC_LDR                     R_AARCH64 = 567
	R_AARCH64_TLSDESC_ADD                     R_AARCH64 = 568
	R_AARCH64_TLSDESC_CALL                    R_AARCH64 = 569
	R_AARCH64_TLSLE_LDST128_TPREL_LO12        R_AARCH64 = 570
	R_AARCH64_TLSLE_LDST128_TPREL_LO12_NC     R_AARCH64 = 571
	R_AARCH64_TLSLD_LDST128_DTPREL_LO12       R_AARCH64 = 572
	R_AARCH64_TLSLD_LDST128_DTPREL_LO12_NC    R_AARCH64 = 573
	R_AARCH64_COPY                            R_AARCH64 = 1024
	R_AARCH64_GLOB_DAT                        R_AARCH64 = 1025
	R_AARCH64_JUMP_SLOT                       R_AARCH64 = 1026
	R_AARCH64_RELATIVE                        R_AARCH64 = 1027
	R_AARCH64_TLS_DTPMOD64                    R_AARCH64 = 1028
	R_AARCH64_TLS_DTPREL64                    R_AARCH64 = 1029
	R_AARCH64_TLS_TPREL64                     R_AARCH64 = 1030
	R_AARCH64_TLSDESC                         R_AARCH64 = 1031
	R_AARCH64_IRELATIVE                       R_AARCH64 = 1032
)

(R_AARCH64) GoString <- go1.4

1
func (i R_AARCH64) GoString() string

(R_AARCH64) String <- go1.4

1
func (i R_AARCH64) String() string

type R_ALPHA

1
type R_ALPHA int

Relocation types for Alpha.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
const (
	R_ALPHA_NONE           R_ALPHA = 0  /* No reloc */
	R_ALPHA_REFLONG        R_ALPHA = 1  /* Direct 32 bit */
	R_ALPHA_REFQUAD        R_ALPHA = 2  /* Direct 64 bit */
	R_ALPHA_GPREL32        R_ALPHA = 3  /* GP relative 32 bit */
	R_ALPHA_LITERAL        R_ALPHA = 4  /* GP relative 16 bit w/optimization */
	R_ALPHA_LITUSE         R_ALPHA = 5  /* Optimization hint for LITERAL */
	R_ALPHA_GPDISP         R_ALPHA = 6  /* Add displacement to GP */
	R_ALPHA_BRADDR         R_ALPHA = 7  /* PC+4 relative 23 bit shifted */
	R_ALPHA_HINT           R_ALPHA = 8  /* PC+4 relative 16 bit shifted */
	R_ALPHA_SREL16         R_ALPHA = 9  /* PC relative 16 bit */
	R_ALPHA_SREL32         R_ALPHA = 10 /* PC relative 32 bit */
	R_ALPHA_SREL64         R_ALPHA = 11 /* PC relative 64 bit */
	R_ALPHA_OP_PUSH        R_ALPHA = 12 /* OP stack push */
	R_ALPHA_OP_STORE       R_ALPHA = 13 /* OP stack pop and store */
	R_ALPHA_OP_PSUB        R_ALPHA = 14 /* OP stack subtract */
	R_ALPHA_OP_PRSHIFT     R_ALPHA = 15 /* OP stack right shift */
	R_ALPHA_GPVALUE        R_ALPHA = 16
	R_ALPHA_GPRELHIGH      R_ALPHA = 17
	R_ALPHA_GPRELLOW       R_ALPHA = 18
	R_ALPHA_IMMED_GP_16    R_ALPHA = 19
	R_ALPHA_IMMED_GP_HI32  R_ALPHA = 20
	R_ALPHA_IMMED_SCN_HI32 R_ALPHA = 21
	R_ALPHA_IMMED_BR_HI32  R_ALPHA = 22
	R_ALPHA_IMMED_LO32     R_ALPHA = 23
	R_ALPHA_COPY           R_ALPHA = 24 /* Copy symbol at runtime */
	R_ALPHA_GLOB_DAT       R_ALPHA = 25 /* Create GOT entry */
	R_ALPHA_JMP_SLOT       R_ALPHA = 26 /* Create PLT entry */
	R_ALPHA_RELATIVE       R_ALPHA = 27 /* Adjust by program base */
)

(R_ALPHA) GoString

1
func (i R_ALPHA) GoString() string

(R_ALPHA) String

1
func (i R_ALPHA) String() string

type R_ARM

1
type R_ARM int

Relocation types for ARM.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
const (
	R_ARM_NONE               R_ARM = 0 /* No relocation. */
	R_ARM_PC24               R_ARM = 1
	R_ARM_ABS32              R_ARM = 2
	R_ARM_REL32              R_ARM = 3
	R_ARM_PC13               R_ARM = 4
	R_ARM_ABS16              R_ARM = 5
	R_ARM_ABS12              R_ARM = 6
	R_ARM_THM_ABS5           R_ARM = 7
	R_ARM_ABS8               R_ARM = 8
	R_ARM_SBREL32            R_ARM = 9
	R_ARM_THM_PC22           R_ARM = 10
	R_ARM_THM_PC8            R_ARM = 11
	R_ARM_AMP_VCALL9         R_ARM = 12
	R_ARM_SWI24              R_ARM = 13
	R_ARM_THM_SWI8           R_ARM = 14
	R_ARM_XPC25              R_ARM = 15
	R_ARM_THM_XPC22          R_ARM = 16
	R_ARM_TLS_DTPMOD32       R_ARM = 17
	R_ARM_TLS_DTPOFF32       R_ARM = 18
	R_ARM_TLS_TPOFF32        R_ARM = 19
	R_ARM_COPY               R_ARM = 20 /* Copy data from shared object. */
	R_ARM_GLOB_DAT           R_ARM = 21 /* Set GOT entry to data address. */
	R_ARM_JUMP_SLOT          R_ARM = 22 /* Set GOT entry to code address. */
	R_ARM_RELATIVE           R_ARM = 23 /* Add load address of shared object. */
	R_ARM_GOTOFF             R_ARM = 24 /* Add GOT-relative symbol address. */
	R_ARM_GOTPC              R_ARM = 25 /* Add PC-relative GOT table address. */
	R_ARM_GOT32              R_ARM = 26 /* Add PC-relative GOT offset. */
	R_ARM_PLT32              R_ARM = 27 /* Add PC-relative PLT offset. */
	R_ARM_CALL               R_ARM = 28
	R_ARM_JUMP24             R_ARM = 29
	R_ARM_THM_JUMP24         R_ARM = 30
	R_ARM_BASE_ABS           R_ARM = 31
	R_ARM_ALU_PCREL_7_0      R_ARM = 32
	R_ARM_ALU_PCREL_15_8     R_ARM = 33
	R_ARM_ALU_PCREL_23_15    R_ARM = 34
	R_ARM_LDR_SBREL_11_10_NC R_ARM = 35
	R_ARM_ALU_SBREL_19_12_NC R_ARM = 36
	R_ARM_ALU_SBREL_27_20_CK R_ARM = 37
	R_ARM_TARGET1            R_ARM = 38
	R_ARM_SBREL31            R_ARM = 39
	R_ARM_V4BX               R_ARM = 40
	R_ARM_TARGET2            R_ARM = 41
	R_ARM_PREL31             R_ARM = 42
	R_ARM_MOVW_ABS_NC        R_ARM = 43
	R_ARM_MOVT_ABS           R_ARM = 44
	R_ARM_MOVW_PREL_NC       R_ARM = 45
	R_ARM_MOVT_PREL          R_ARM = 46
	R_ARM_THM_MOVW_ABS_NC    R_ARM = 47
	R_ARM_THM_MOVT_ABS       R_ARM = 48
	R_ARM_THM_MOVW_PREL_NC   R_ARM = 49
	R_ARM_THM_MOVT_PREL      R_ARM = 50
	R_ARM_THM_JUMP19         R_ARM = 51
	R_ARM_THM_JUMP6          R_ARM = 52
	R_ARM_THM_ALU_PREL_11_0  R_ARM = 53
	R_ARM_THM_PC12           R_ARM = 54
	R_ARM_ABS32_NOI          R_ARM = 55
	R_ARM_REL32_NOI          R_ARM = 56
	R_ARM_ALU_PC_G0_NC       R_ARM = 57
	R_ARM_ALU_PC_G0          R_ARM = 58
	R_ARM_ALU_PC_G1_NC       R_ARM = 59
	R_ARM_ALU_PC_G1          R_ARM = 60
	R_ARM_ALU_PC_G2          R_ARM = 61
	R_ARM_LDR_PC_G1          R_ARM = 62
	R_ARM_LDR_PC_G2          R_ARM = 63
	R_ARM_LDRS_PC_G0         R_ARM = 64
	R_ARM_LDRS_PC_G1         R_ARM = 65
	R_ARM_LDRS_PC_G2         R_ARM = 66
	R_ARM_LDC_PC_G0          R_ARM = 67
	R_ARM_LDC_PC_G1          R_ARM = 68
	R_ARM_LDC_PC_G2          R_ARM = 69
	R_ARM_ALU_SB_G0_NC       R_ARM = 70
	R_ARM_ALU_SB_G0          R_ARM = 71
	R_ARM_ALU_SB_G1_NC       R_ARM = 72
	R_ARM_ALU_SB_G1          R_ARM = 73
	R_ARM_ALU_SB_G2          R_ARM = 74
	R_ARM_LDR_SB_G0          R_ARM = 75
	R_ARM_LDR_SB_G1          R_ARM = 76
	R_ARM_LDR_SB_G2          R_ARM = 77
	R_ARM_LDRS_SB_G0         R_ARM = 78
	R_ARM_LDRS_SB_G1         R_ARM = 79
	R_ARM_LDRS_SB_G2         R_ARM = 80
	R_ARM_LDC_SB_G0          R_ARM = 81
	R_ARM_LDC_SB_G1          R_ARM = 82
	R_ARM_LDC_SB_G2          R_ARM = 83
	R_ARM_MOVW_BREL_NC       R_ARM = 84
	R_ARM_MOVT_BREL          R_ARM = 85
	R_ARM_MOVW_BREL          R_ARM = 86
	R_ARM_THM_MOVW_BREL_NC   R_ARM = 87
	R_ARM_THM_MOVT_BREL      R_ARM = 88
	R_ARM_THM_MOVW_BREL      R_ARM = 89
	R_ARM_TLS_GOTDESC        R_ARM = 90
	R_ARM_TLS_CALL           R_ARM = 91
	R_ARM_TLS_DESCSEQ        R_ARM = 92
	R_ARM_THM_TLS_CALL       R_ARM = 93
	R_ARM_PLT32_ABS          R_ARM = 94
	R_ARM_GOT_ABS            R_ARM = 95
	R_ARM_GOT_PREL           R_ARM = 96
	R_ARM_GOT_BREL12         R_ARM = 97
	R_ARM_GOTOFF12           R_ARM = 98
	R_ARM_GOTRELAX           R_ARM = 99
	R_ARM_GNU_VTENTRY        R_ARM = 100
	R_ARM_GNU_VTINHERIT      R_ARM = 101
	R_ARM_THM_JUMP11         R_ARM = 102
	R_ARM_THM_JUMP8          R_ARM = 103
	R_ARM_TLS_GD32           R_ARM = 104
	R_ARM_TLS_LDM32          R_ARM = 105
	R_ARM_TLS_LDO32          R_ARM = 106
	R_ARM_TLS_IE32           R_ARM = 107
	R_ARM_TLS_LE32           R_ARM = 108
	R_ARM_TLS_LDO12          R_ARM = 109
	R_ARM_TLS_LE12           R_ARM = 110
	R_ARM_TLS_IE12GP         R_ARM = 111
	R_ARM_PRIVATE_0          R_ARM = 112
	R_ARM_PRIVATE_1          R_ARM = 113
	R_ARM_PRIVATE_2          R_ARM = 114
	R_ARM_PRIVATE_3          R_ARM = 115
	R_ARM_PRIVATE_4          R_ARM = 116
	R_ARM_PRIVATE_5          R_ARM = 117
	R_ARM_PRIVATE_6          R_ARM = 118
	R_ARM_PRIVATE_7          R_ARM = 119
	R_ARM_PRIVATE_8          R_ARM = 120
	R_ARM_PRIVATE_9          R_ARM = 121
	R_ARM_PRIVATE_10         R_ARM = 122
	R_ARM_PRIVATE_11         R_ARM = 123
	R_ARM_PRIVATE_12         R_ARM = 124
	R_ARM_PRIVATE_13         R_ARM = 125
	R_ARM_PRIVATE_14         R_ARM = 126
	R_ARM_PRIVATE_15         R_ARM = 127
	R_ARM_ME_TOO             R_ARM = 128
	R_ARM_THM_TLS_DESCSEQ16  R_ARM = 129
	R_ARM_THM_TLS_DESCSEQ32  R_ARM = 130
	R_ARM_THM_GOT_BREL12     R_ARM = 131
	R_ARM_THM_ALU_ABS_G0_NC  R_ARM = 132
	R_ARM_THM_ALU_ABS_G1_NC  R_ARM = 133
	R_ARM_THM_ALU_ABS_G2_NC  R_ARM = 134
	R_ARM_THM_ALU_ABS_G3     R_ARM = 135
	R_ARM_IRELATIVE          R_ARM = 160
	R_ARM_RXPC25             R_ARM = 249
	R_ARM_RSBREL32           R_ARM = 250
	R_ARM_THM_RPC22          R_ARM = 251
	R_ARM_RREL32             R_ARM = 252
	R_ARM_RABS32             R_ARM = 253
	R_ARM_RPC24              R_ARM = 254
	R_ARM_RBASE              R_ARM = 255
)

(R_ARM) GoString

1
func (i R_ARM) GoString() string

(R_ARM) String

1
func (i R_ARM) String() string

type R_LARCH <- go1.19

1
type R_LARCH int

Relocation types for LoongArch.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
const (
	R_LARCH_NONE                       R_LARCH = 0
	R_LARCH_32                         R_LARCH = 1
	R_LARCH_64                         R_LARCH = 2
	R_LARCH_RELATIVE                   R_LARCH = 3
	R_LARCH_COPY                       R_LARCH = 4
	R_LARCH_JUMP_SLOT                  R_LARCH = 5
	R_LARCH_TLS_DTPMOD32               R_LARCH = 6
	R_LARCH_TLS_DTPMOD64               R_LARCH = 7
	R_LARCH_TLS_DTPREL32               R_LARCH = 8
	R_LARCH_TLS_DTPREL64               R_LARCH = 9
	R_LARCH_TLS_TPREL32                R_LARCH = 10
	R_LARCH_TLS_TPREL64                R_LARCH = 11
	R_LARCH_IRELATIVE                  R_LARCH = 12
	R_LARCH_MARK_LA                    R_LARCH = 20
	R_LARCH_MARK_PCREL                 R_LARCH = 21
	R_LARCH_SOP_PUSH_PCREL             R_LARCH = 22
	R_LARCH_SOP_PUSH_ABSOLUTE          R_LARCH = 23
	R_LARCH_SOP_PUSH_DUP               R_LARCH = 24
	R_LARCH_SOP_PUSH_GPREL             R_LARCH = 25
	R_LARCH_SOP_PUSH_TLS_TPREL         R_LARCH = 26
	R_LARCH_SOP_PUSH_TLS_GOT           R_LARCH = 27
	R_LARCH_SOP_PUSH_TLS_GD            R_LARCH = 28
	R_LARCH_SOP_PUSH_PLT_PCREL         R_LARCH = 29
	R_LARCH_SOP_ASSERT                 R_LARCH = 30
	R_LARCH_SOP_NOT                    R_LARCH = 31
	R_LARCH_SOP_SUB                    R_LARCH = 32
	R_LARCH_SOP_SL                     R_LARCH = 33
	R_LARCH_SOP_SR                     R_LARCH = 34
	R_LARCH_SOP_ADD                    R_LARCH = 35
	R_LARCH_SOP_AND                    R_LARCH = 36
	R_LARCH_SOP_IF_ELSE                R_LARCH = 37
	R_LARCH_SOP_POP_32_S_10_5          R_LARCH = 38
	R_LARCH_SOP_POP_32_U_10_12         R_LARCH = 39
	R_LARCH_SOP_POP_32_S_10_12         R_LARCH = 40
	R_LARCH_SOP_POP_32_S_10_16         R_LARCH = 41
	R_LARCH_SOP_POP_32_S_10_16_S2      R_LARCH = 42
	R_LARCH_SOP_POP_32_S_5_20          R_LARCH = 43
	R_LARCH_SOP_POP_32_S_0_5_10_16_S2  R_LARCH = 44
	R_LARCH_SOP_POP_32_S_0_10_10_16_S2 R_LARCH = 45
	R_LARCH_SOP_POP_32_U               R_LARCH = 46
	R_LARCH_ADD8                       R_LARCH = 47
	R_LARCH_ADD16                      R_LARCH = 48
	R_LARCH_ADD24                      R_LARCH = 49
	R_LARCH_ADD32                      R_LARCH = 50
	R_LARCH_ADD64                      R_LARCH = 51
	R_LARCH_SUB8                       R_LARCH = 52
	R_LARCH_SUB16                      R_LARCH = 53
	R_LARCH_SUB24                      R_LARCH = 54
	R_LARCH_SUB32                      R_LARCH = 55
	R_LARCH_SUB64                      R_LARCH = 56
	R_LARCH_GNU_VTINHERIT              R_LARCH = 57
	R_LARCH_GNU_VTENTRY                R_LARCH = 58
	R_LARCH_B16                        R_LARCH = 64
	R_LARCH_B21                        R_LARCH = 65
	R_LARCH_B26                        R_LARCH = 66
	R_LARCH_ABS_HI20                   R_LARCH = 67
	R_LARCH_ABS_LO12                   R_LARCH = 68
	R_LARCH_ABS64_LO20                 R_LARCH = 69
	R_LARCH_ABS64_HI12                 R_LARCH = 70
	R_LARCH_PCALA_HI20                 R_LARCH = 71
	R_LARCH_PCALA_LO12                 R_LARCH = 72
	R_LARCH_PCALA64_LO20               R_LARCH = 73
	R_LARCH_PCALA64_HI12               R_LARCH = 74
	R_LARCH_GOT_PC_HI20                R_LARCH = 75
	R_LARCH_GOT_PC_LO12                R_LARCH = 76
	R_LARCH_GOT64_PC_LO20              R_LARCH = 77
	R_LARCH_GOT64_PC_HI12              R_LARCH = 78
	R_LARCH_GOT_HI20                   R_LARCH = 79
	R_LARCH_GOT_LO12                   R_LARCH = 80
	R_LARCH_GOT64_LO20                 R_LARCH = 81
	R_LARCH_GOT64_HI12                 R_LARCH = 82
	R_LARCH_TLS_LE_HI20                R_LARCH = 83
	R_LARCH_TLS_LE_LO12                R_LARCH = 84
	R_LARCH_TLS_LE64_LO20              R_LARCH = 85
	R_LARCH_TLS_LE64_HI12              R_LARCH = 86
	R_LARCH_TLS_IE_PC_HI20             R_LARCH = 87
	R_LARCH_TLS_IE_PC_LO12             R_LARCH = 88
	R_LARCH_TLS_IE64_PC_LO20           R_LARCH = 89
	R_LARCH_TLS_IE64_PC_HI12           R_LARCH = 90
	R_LARCH_TLS_IE_HI20                R_LARCH = 91
	R_LARCH_TLS_IE_LO12                R_LARCH = 92
	R_LARCH_TLS_IE64_LO20              R_LARCH = 93
	R_LARCH_TLS_IE64_HI12              R_LARCH = 94
	R_LARCH_TLS_LD_PC_HI20             R_LARCH = 95
	R_LARCH_TLS_LD_HI20                R_LARCH = 96
	R_LARCH_TLS_GD_PC_HI20             R_LARCH = 97
	R_LARCH_TLS_GD_HI20                R_LARCH = 98
	R_LARCH_32_PCREL                   R_LARCH = 99
	R_LARCH_RELAX                      R_LARCH = 100
)

(R_LARCH) GoString <- go1.19

1
func (i R_LARCH) GoString() string

(R_LARCH) String <- go1.19

1
func (i R_LARCH) String() string

type R_MIPS <- go1.6

1
type R_MIPS int

Relocation types for MIPS.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
const (
	R_MIPS_NONE          R_MIPS = 0
	R_MIPS_16            R_MIPS = 1
	R_MIPS_32            R_MIPS = 2
	R_MIPS_REL32         R_MIPS = 3
	R_MIPS_26            R_MIPS = 4
	R_MIPS_HI16          R_MIPS = 5  /* high 16 bits of symbol value */
	R_MIPS_LO16          R_MIPS = 6  /* low 16 bits of symbol value */
	R_MIPS_GPREL16       R_MIPS = 7  /* GP-relative reference  */
	R_MIPS_LITERAL       R_MIPS = 8  /* Reference to literal section  */
	R_MIPS_GOT16         R_MIPS = 9  /* Reference to global offset table */
	R_MIPS_PC16          R_MIPS = 10 /* 16 bit PC relative reference */
	R_MIPS_CALL16        R_MIPS = 11 /* 16 bit call through glbl offset tbl */
	R_MIPS_GPREL32       R_MIPS = 12
	R_MIPS_SHIFT5        R_MIPS = 16
	R_MIPS_SHIFT6        R_MIPS = 17
	R_MIPS_64            R_MIPS = 18
	R_MIPS_GOT_DISP      R_MIPS = 19
	R_MIPS_GOT_PAGE      R_MIPS = 20
	R_MIPS_GOT_OFST      R_MIPS = 21
	R_MIPS_GOT_HI16      R_MIPS = 22
	R_MIPS_GOT_LO16      R_MIPS = 23
	R_MIPS_SUB           R_MIPS = 24
	R_MIPS_INSERT_A      R_MIPS = 25
	R_MIPS_INSERT_B      R_MIPS = 26
	R_MIPS_DELETE        R_MIPS = 27
	R_MIPS_HIGHER        R_MIPS = 28
	R_MIPS_HIGHEST       R_MIPS = 29
	R_MIPS_CALL_HI16     R_MIPS = 30
	R_MIPS_CALL_LO16     R_MIPS = 31
	R_MIPS_SCN_DISP      R_MIPS = 32
	R_MIPS_REL16         R_MIPS = 33
	R_MIPS_ADD_IMMEDIATE R_MIPS = 34
	R_MIPS_PJUMP         R_MIPS = 35
	R_MIPS_RELGOT        R_MIPS = 36
	R_MIPS_JALR          R_MIPS = 37

	R_MIPS_TLS_DTPMOD32    R_MIPS = 38 /* Module number 32 bit */
	R_MIPS_TLS_DTPREL32    R_MIPS = 39 /* Module-relative offset 32 bit */
	R_MIPS_TLS_DTPMOD64    R_MIPS = 40 /* Module number 64 bit */
	R_MIPS_TLS_DTPREL64    R_MIPS = 41 /* Module-relative offset 64 bit */
	R_MIPS_TLS_GD          R_MIPS = 42 /* 16 bit GOT offset for GD */
	R_MIPS_TLS_LDM         R_MIPS = 43 /* 16 bit GOT offset for LDM */
	R_MIPS_TLS_DTPREL_HI16 R_MIPS = 44 /* Module-relative offset, high 16 bits */
	R_MIPS_TLS_DTPREL_LO16 R_MIPS = 45 /* Module-relative offset, low 16 bits */
	R_MIPS_TLS_GOTTPREL    R_MIPS = 46 /* 16 bit GOT offset for IE */
	R_MIPS_TLS_TPREL32     R_MIPS = 47 /* TP-relative offset, 32 bit */
	R_MIPS_TLS_TPREL64     R_MIPS = 48 /* TP-relative offset, 64 bit */
	R_MIPS_TLS_TPREL_HI16  R_MIPS = 49 /* TP-relative offset, high 16 bits */
	R_MIPS_TLS_TPREL_LO16  R_MIPS = 50 /* TP-relative offset, low 16 bits */
)

(R_MIPS) GoString <- go1.6

1
func (i R_MIPS) GoString() string

(R_MIPS) String <- go1.6

1
func (i R_MIPS) String() string

type R_PPC

1
type R_PPC int

Relocation types for PowerPC.

Values that are shared by both R_PPC and R_PPC64 are prefixed with R_POWERPC_ in the ELF standard. For the R_PPC type, the relevant shared relocations have been renamed with the prefix R_PPC_. The original name follows the value in a comment.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
const (
	R_PPC_NONE            R_PPC = 0  // R_POWERPC_NONE
	R_PPC_ADDR32          R_PPC = 1  // R_POWERPC_ADDR32
	R_PPC_ADDR24          R_PPC = 2  // R_POWERPC_ADDR24
	R_PPC_ADDR16          R_PPC = 3  // R_POWERPC_ADDR16
	R_PPC_ADDR16_LO       R_PPC = 4  // R_POWERPC_ADDR16_LO
	R_PPC_ADDR16_HI       R_PPC = 5  // R_POWERPC_ADDR16_HI
	R_PPC_ADDR16_HA       R_PPC = 6  // R_POWERPC_ADDR16_HA
	R_PPC_ADDR14          R_PPC = 7  // R_POWERPC_ADDR14
	R_PPC_ADDR14_BRTAKEN  R_PPC = 8  // R_POWERPC_ADDR14_BRTAKEN
	R_PPC_ADDR14_BRNTAKEN R_PPC = 9  // R_POWERPC_ADDR14_BRNTAKEN
	R_PPC_REL24           R_PPC = 10 // R_POWERPC_REL24
	R_PPC_REL14           R_PPC = 11 // R_POWERPC_REL14
	R_PPC_REL14_BRTAKEN   R_PPC = 12 // R_POWERPC_REL14_BRTAKEN
	R_PPC_REL14_BRNTAKEN  R_PPC = 13 // R_POWERPC_REL14_BRNTAKEN
	R_PPC_GOT16           R_PPC = 14 // R_POWERPC_GOT16
	R_PPC_GOT16_LO        R_PPC = 15 // R_POWERPC_GOT16_LO
	R_PPC_GOT16_HI        R_PPC = 16 // R_POWERPC_GOT16_HI
	R_PPC_GOT16_HA        R_PPC = 17 // R_POWERPC_GOT16_HA
	R_PPC_PLTREL24        R_PPC = 18
	R_PPC_COPY            R_PPC = 19 // R_POWERPC_COPY
	R_PPC_GLOB_DAT        R_PPC = 20 // R_POWERPC_GLOB_DAT
	R_PPC_JMP_SLOT        R_PPC = 21 // R_POWERPC_JMP_SLOT
	R_PPC_RELATIVE        R_PPC = 22 // R_POWERPC_RELATIVE
	R_PPC_LOCAL24PC       R_PPC = 23
	R_PPC_UADDR32         R_PPC = 24 // R_POWERPC_UADDR32
	R_PPC_UADDR16         R_PPC = 25 // R_POWERPC_UADDR16
	R_PPC_REL32           R_PPC = 26 // R_POWERPC_REL32
	R_PPC_PLT32           R_PPC = 27 // R_POWERPC_PLT32
	R_PPC_PLTREL32        R_PPC = 28 // R_POWERPC_PLTREL32
	R_PPC_PLT16_LO        R_PPC = 29 // R_POWERPC_PLT16_LO
	R_PPC_PLT16_HI        R_PPC = 30 // R_POWERPC_PLT16_HI
	R_PPC_PLT16_HA        R_PPC = 31 // R_POWERPC_PLT16_HA
	R_PPC_SDAREL16        R_PPC = 32
	R_PPC_SECTOFF         R_PPC = 33 // R_POWERPC_SECTOFF
	R_PPC_SECTOFF_LO      R_PPC = 34 // R_POWERPC_SECTOFF_LO
	R_PPC_SECTOFF_HI      R_PPC = 35 // R_POWERPC_SECTOFF_HI
	R_PPC_SECTOFF_HA      R_PPC = 36 // R_POWERPC_SECTOFF_HA
	R_PPC_TLS             R_PPC = 67 // R_POWERPC_TLS
	R_PPC_DTPMOD32        R_PPC = 68 // R_POWERPC_DTPMOD32
	R_PPC_TPREL16         R_PPC = 69 // R_POWERPC_TPREL16
	R_PPC_TPREL16_LO      R_PPC = 70 // R_POWERPC_TPREL16_LO
	R_PPC_TPREL16_HI      R_PPC = 71 // R_POWERPC_TPREL16_HI
	R_PPC_TPREL16_HA      R_PPC = 72 // R_POWERPC_TPREL16_HA
	R_PPC_TPREL32         R_PPC = 73 // R_POWERPC_TPREL32
	R_PPC_DTPREL16        R_PPC = 74 // R_POWERPC_DTPREL16
	R_PPC_DTPREL16_LO     R_PPC = 75 // R_POWERPC_DTPREL16_LO
	R_PPC_DTPREL16_HI     R_PPC = 76 // R_POWERPC_DTPREL16_HI
	R_PPC_DTPREL16_HA     R_PPC = 77 // R_POWERPC_DTPREL16_HA
	R_PPC_DTPREL32        R_PPC = 78 // R_POWERPC_DTPREL32
	R_PPC_GOT_TLSGD16     R_PPC = 79 // R_POWERPC_GOT_TLSGD16
	R_PPC_GOT_TLSGD16_LO  R_PPC = 80 // R_POWERPC_GOT_TLSGD16_LO
	R_PPC_GOT_TLSGD16_HI  R_PPC = 81 // R_POWERPC_GOT_TLSGD16_HI
	R_PPC_GOT_TLSGD16_HA  R_PPC = 82 // R_POWERPC_GOT_TLSGD16_HA
	R_PPC_GOT_TLSLD16     R_PPC = 83 // R_POWERPC_GOT_TLSLD16
	R_PPC_GOT_TLSLD16_LO  R_PPC = 84 // R_POWERPC_GOT_TLSLD16_LO
	R_PPC_GOT_TLSLD16_HI  R_PPC = 85 // R_POWERPC_GOT_TLSLD16_HI
	R_PPC_GOT_TLSLD16_HA  R_PPC = 86 // R_POWERPC_GOT_TLSLD16_HA
	R_PPC_GOT_TPREL16     R_PPC = 87 // R_POWERPC_GOT_TPREL16
	R_PPC_GOT_TPREL16_LO  R_PPC = 88 // R_POWERPC_GOT_TPREL16_LO
	R_PPC_GOT_TPREL16_HI  R_PPC = 89 // R_POWERPC_GOT_TPREL16_HI
	R_PPC_GOT_TPREL16_HA  R_PPC = 90 // R_POWERPC_GOT_TPREL16_HA
	R_PPC_EMB_NADDR32     R_PPC = 101
	R_PPC_EMB_NADDR16     R_PPC = 102
	R_PPC_EMB_NADDR16_LO  R_PPC = 103
	R_PPC_EMB_NADDR16_HI  R_PPC = 104
	R_PPC_EMB_NADDR16_HA  R_PPC = 105
	R_PPC_EMB_SDAI16      R_PPC = 106
	R_PPC_EMB_SDA2I16     R_PPC = 107
	R_PPC_EMB_SDA2REL     R_PPC = 108
	R_PPC_EMB_SDA21       R_PPC = 109
	R_PPC_EMB_MRKREF      R_PPC = 110
	R_PPC_EMB_RELSEC16    R_PPC = 111
	R_PPC_EMB_RELST_LO    R_PPC = 112
	R_PPC_EMB_RELST_HI    R_PPC = 113
	R_PPC_EMB_RELST_HA    R_PPC = 114
	R_PPC_EMB_BIT_FLD     R_PPC = 115
	R_PPC_EMB_RELSDA      R_PPC = 116
)

(R_PPC) GoString

1
func (i R_PPC) GoString() string

(R_PPC) String

1
func (i R_PPC) String() string

type R_PPC64 <- go1.5

1
type R_PPC64 int

Relocation types for 64-bit PowerPC or Power Architecture processors.

Values that are shared by both R_PPC and R_PPC64 are prefixed with R_POWERPC_ in the ELF standard. For the R_PPC64 type, the relevant shared relocations have been renamed with the prefix R_PPC64_. The original name follows the value in a comment.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
const (
	R_PPC64_NONE               R_PPC64 = 0  // R_POWERPC_NONE
	R_PPC64_ADDR32             R_PPC64 = 1  // R_POWERPC_ADDR32
	R_PPC64_ADDR24             R_PPC64 = 2  // R_POWERPC_ADDR24
	R_PPC64_ADDR16             R_PPC64 = 3  // R_POWERPC_ADDR16
	R_PPC64_ADDR16_LO          R_PPC64 = 4  // R_POWERPC_ADDR16_LO
	R_PPC64_ADDR16_HI          R_PPC64 = 5  // R_POWERPC_ADDR16_HI
	R_PPC64_ADDR16_HA          R_PPC64 = 6  // R_POWERPC_ADDR16_HA
	R_PPC64_ADDR14             R_PPC64 = 7  // R_POWERPC_ADDR14
	R_PPC64_ADDR14_BRTAKEN     R_PPC64 = 8  // R_POWERPC_ADDR14_BRTAKEN
	R_PPC64_ADDR14_BRNTAKEN    R_PPC64 = 9  // R_POWERPC_ADDR14_BRNTAKEN
	R_PPC64_REL24              R_PPC64 = 10 // R_POWERPC_REL24
	R_PPC64_REL14              R_PPC64 = 11 // R_POWERPC_REL14
	R_PPC64_REL14_BRTAKEN      R_PPC64 = 12 // R_POWERPC_REL14_BRTAKEN
	R_PPC64_REL14_BRNTAKEN     R_PPC64 = 13 // R_POWERPC_REL14_BRNTAKEN
	R_PPC64_GOT16              R_PPC64 = 14 // R_POWERPC_GOT16
	R_PPC64_GOT16_LO           R_PPC64 = 15 // R_POWERPC_GOT16_LO
	R_PPC64_GOT16_HI           R_PPC64 = 16 // R_POWERPC_GOT16_HI
	R_PPC64_GOT16_HA           R_PPC64 = 17 // R_POWERPC_GOT16_HA
	R_PPC64_COPY               R_PPC64 = 19 // R_POWERPC_COPY
	R_PPC64_GLOB_DAT           R_PPC64 = 20 // R_POWERPC_GLOB_DAT
	R_PPC64_JMP_SLOT           R_PPC64 = 21 // R_POWERPC_JMP_SLOT
	R_PPC64_RELATIVE           R_PPC64 = 22 // R_POWERPC_RELATIVE
	R_PPC64_UADDR32            R_PPC64 = 24 // R_POWERPC_UADDR32
	R_PPC64_UADDR16            R_PPC64 = 25 // R_POWERPC_UADDR16
	R_PPC64_REL32              R_PPC64 = 26 // R_POWERPC_REL32
	R_PPC64_PLT32              R_PPC64 = 27 // R_POWERPC_PLT32
	R_PPC64_PLTREL32           R_PPC64 = 28 // R_POWERPC_PLTREL32
	R_PPC64_PLT16_LO           R_PPC64 = 29 // R_POWERPC_PLT16_LO
	R_PPC64_PLT16_HI           R_PPC64 = 30 // R_POWERPC_PLT16_HI
	R_PPC64_PLT16_HA           R_PPC64 = 31 // R_POWERPC_PLT16_HA
	R_PPC64_SECTOFF            R_PPC64 = 33 // R_POWERPC_SECTOFF
	R_PPC64_SECTOFF_LO         R_PPC64 = 34 // R_POWERPC_SECTOFF_LO
	R_PPC64_SECTOFF_HI         R_PPC64 = 35 // R_POWERPC_SECTOFF_HI
	R_PPC64_SECTOFF_HA         R_PPC64 = 36 // R_POWERPC_SECTOFF_HA
	R_PPC64_REL30              R_PPC64 = 37 // R_POWERPC_ADDR30
	R_PPC64_ADDR64             R_PPC64 = 38
	R_PPC64_ADDR16_HIGHER      R_PPC64 = 39
	R_PPC64_ADDR16_HIGHERA     R_PPC64 = 40
	R_PPC64_ADDR16_HIGHEST     R_PPC64 = 41
	R_PPC64_ADDR16_HIGHESTA    R_PPC64 = 42
	R_PPC64_UADDR64            R_PPC64 = 43
	R_PPC64_REL64              R_PPC64 = 44
	R_PPC64_PLT64              R_PPC64 = 45
	R_PPC64_PLTREL64           R_PPC64 = 46
	R_PPC64_TOC16              R_PPC64 = 47
	R_PPC64_TOC16_LO           R_PPC64 = 48
	R_PPC64_TOC16_HI           R_PPC64 = 49
	R_PPC64_TOC16_HA           R_PPC64 = 50
	R_PPC64_TOC                R_PPC64 = 51
	R_PPC64_PLTGOT16           R_PPC64 = 52
	R_PPC64_PLTGOT16_LO        R_PPC64 = 53
	R_PPC64_PLTGOT16_HI        R_PPC64 = 54
	R_PPC64_PLTGOT16_HA        R_PPC64 = 55
	R_PPC64_ADDR16_DS          R_PPC64 = 56
	R_PPC64_ADDR16_LO_DS       R_PPC64 = 57
	R_PPC64_GOT16_DS           R_PPC64 = 58
	R_PPC64_GOT16_LO_DS        R_PPC64 = 59
	R_PPC64_PLT16_LO_DS        R_PPC64 = 60
	R_PPC64_SECTOFF_DS         R_PPC64 = 61
	R_PPC64_SECTOFF_LO_DS      R_PPC64 = 62
	R_PPC64_TOC16_DS           R_PPC64 = 63
	R_PPC64_TOC16_LO_DS        R_PPC64 = 64
	R_PPC64_PLTGOT16_DS        R_PPC64 = 65
	R_PPC64_PLTGOT_LO_DS       R_PPC64 = 66
	R_PPC64_TLS                R_PPC64 = 67 // R_POWERPC_TLS
	R_PPC64_DTPMOD64           R_PPC64 = 68 // R_POWERPC_DTPMOD64
	R_PPC64_TPREL16            R_PPC64 = 69 // R_POWERPC_TPREL16
	R_PPC64_TPREL16_LO         R_PPC64 = 70 // R_POWERPC_TPREL16_LO
	R_PPC64_TPREL16_HI         R_PPC64 = 71 // R_POWERPC_TPREL16_HI
	R_PPC64_TPREL16_HA         R_PPC64 = 72 // R_POWERPC_TPREL16_HA
	R_PPC64_TPREL64            R_PPC64 = 73 // R_POWERPC_TPREL64
	R_PPC64_DTPREL16           R_PPC64 = 74 // R_POWERPC_DTPREL16
	R_PPC64_DTPREL16_LO        R_PPC64 = 75 // R_POWERPC_DTPREL16_LO
	R_PPC64_DTPREL16_HI        R_PPC64 = 76 // R_POWERPC_DTPREL16_HI
	R_PPC64_DTPREL16_HA        R_PPC64 = 77 // R_POWERPC_DTPREL16_HA
	R_PPC64_DTPREL64           R_PPC64 = 78 // R_POWERPC_DTPREL64
	R_PPC64_GOT_TLSGD16        R_PPC64 = 79 // R_POWERPC_GOT_TLSGD16
	R_PPC64_GOT_TLSGD16_LO     R_PPC64 = 80 // R_POWERPC_GOT_TLSGD16_LO
	R_PPC64_GOT_TLSGD16_HI     R_PPC64 = 81 // R_POWERPC_GOT_TLSGD16_HI
	R_PPC64_GOT_TLSGD16_HA     R_PPC64 = 82 // R_POWERPC_GOT_TLSGD16_HA
	R_PPC64_GOT_TLSLD16        R_PPC64 = 83 // R_POWERPC_GOT_TLSLD16
	R_PPC64_GOT_TLSLD16_LO     R_PPC64 = 84 // R_POWERPC_GOT_TLSLD16_LO
	R_PPC64_GOT_TLSLD16_HI     R_PPC64 = 85 // R_POWERPC_GOT_TLSLD16_HI
	R_PPC64_GOT_TLSLD16_HA     R_PPC64 = 86 // R_POWERPC_GOT_TLSLD16_HA
	R_PPC64_GOT_TPREL16_DS     R_PPC64 = 87 // R_POWERPC_GOT_TPREL16_DS
	R_PPC64_GOT_TPREL16_LO_DS  R_PPC64 = 88 // R_POWERPC_GOT_TPREL16_LO_DS
	R_PPC64_GOT_TPREL16_HI     R_PPC64 = 89 // R_POWERPC_GOT_TPREL16_HI
	R_PPC64_GOT_TPREL16_HA     R_PPC64 = 90 // R_POWERPC_GOT_TPREL16_HA
	R_PPC64_GOT_DTPREL16_DS    R_PPC64 = 91 // R_POWERPC_GOT_DTPREL16_DS
	R_PPC64_GOT_DTPREL16_LO_DS R_PPC64 = 92 // R_POWERPC_GOT_DTPREL16_LO_DS
	R_PPC64_GOT_DTPREL16_HI    R_PPC64 = 93 // R_POWERPC_GOT_DTPREL16_HI
	R_PPC64_GOT_DTPREL16_HA    R_PPC64 = 94 // R_POWERPC_GOT_DTPREL16_HA
	R_PPC64_TPREL16_DS         R_PPC64 = 95
	R_PPC64_TPREL16_LO_DS      R_PPC64 = 96
	R_PPC64_TPREL16_HIGHER     R_PPC64 = 97
	R_PPC64_TPREL16_HIGHERA    R_PPC64 = 98
	R_PPC64_TPREL16_HIGHEST    R_PPC64 = 99
	R_PPC64_TPREL16_HIGHESTA   R_PPC64 = 100
	R_PPC64_DTPREL16_DS        R_PPC64 = 101
	R_PPC64_DTPREL16_LO_DS     R_PPC64 = 102
	R_PPC64_DTPREL16_HIGHER    R_PPC64 = 103
	R_PPC64_DTPREL16_HIGHERA   R_PPC64 = 104
	R_PPC64_DTPREL16_HIGHEST   R_PPC64 = 105
	R_PPC64_DTPREL16_HIGHESTA  R_PPC64 = 106
	R_PPC64_TLSGD              R_PPC64 = 107
	R_PPC64_TLSLD              R_PPC64 = 108
	R_PPC64_TOCSAVE            R_PPC64 = 109
	R_PPC64_ADDR16_HIGH        R_PPC64 = 110
	R_PPC64_ADDR16_HIGHA       R_PPC64 = 111
	R_PPC64_TPREL16_HIGH       R_PPC64 = 112
	R_PPC64_TPREL16_HIGHA      R_PPC64 = 113
	R_PPC64_DTPREL16_HIGH      R_PPC64 = 114
	R_PPC64_DTPREL16_HIGHA     R_PPC64 = 115
	R_PPC64_REL24_NOTOC        R_PPC64 = 116
	R_PPC64_ADDR64_LOCAL       R_PPC64 = 117
	R_PPC64_ENTRY              R_PPC64 = 118
	R_PPC64_PLTSEQ             R_PPC64 = 119
	R_PPC64_PLTCALL            R_PPC64 = 120
	R_PPC64_PLTSEQ_NOTOC       R_PPC64 = 121
	R_PPC64_PLTCALL_NOTOC      R_PPC64 = 122
	R_PPC64_PCREL_OPT          R_PPC64 = 123
	R_PPC64_D34                R_PPC64 = 128
	R_PPC64_D34_LO             R_PPC64 = 129
	R_PPC64_D34_HI30           R_PPC64 = 130
	R_PPC64_D34_HA30           R_PPC64 = 131
	R_PPC64_PCREL34            R_PPC64 = 132
	R_PPC64_GOT_PCREL34        R_PPC64 = 133
	R_PPC64_PLT_PCREL34        R_PPC64 = 134
	R_PPC64_PLT_PCREL34_NOTOC  R_PPC64 = 135
	R_PPC64_ADDR16_HIGHER34    R_PPC64 = 136
	R_PPC64_ADDR16_HIGHERA34   R_PPC64 = 137
	R_PPC64_ADDR16_HIGHEST34   R_PPC64 = 138
	R_PPC64_ADDR16_HIGHESTA34  R_PPC64 = 139
	R_PPC64_REL16_HIGHER34     R_PPC64 = 140
	R_PPC64_REL16_HIGHERA34    R_PPC64 = 141
	R_PPC64_REL16_HIGHEST34    R_PPC64 = 142
	R_PPC64_REL16_HIGHESTA34   R_PPC64 = 143
	R_PPC64_D28                R_PPC64 = 144
	R_PPC64_PCREL28            R_PPC64 = 145
	R_PPC64_TPREL34            R_PPC64 = 146
	R_PPC64_DTPREL34           R_PPC64 = 147
	R_PPC64_GOT_TLSGD_PCREL34  R_PPC64 = 148
	R_PPC64_GOT_TLSLD_PCREL34  R_PPC64 = 149
	R_PPC64_GOT_TPREL_PCREL34  R_PPC64 = 150
	R_PPC64_GOT_DTPREL_PCREL34 R_PPC64 = 151
	R_PPC64_REL16_HIGH         R_PPC64 = 240
	R_PPC64_REL16_HIGHA        R_PPC64 = 241
	R_PPC64_REL16_HIGHER       R_PPC64 = 242
	R_PPC64_REL16_HIGHERA      R_PPC64 = 243
	R_PPC64_REL16_HIGHEST      R_PPC64 = 244
	R_PPC64_REL16_HIGHESTA     R_PPC64 = 245
	R_PPC64_REL16DX_HA         R_PPC64 = 246 // R_POWERPC_REL16DX_HA
	R_PPC64_JMP_IREL           R_PPC64 = 247
	R_PPC64_IRELATIVE          R_PPC64 = 248 // R_POWERPC_IRELATIVE
	R_PPC64_REL16              R_PPC64 = 249 // R_POWERPC_REL16
	R_PPC64_REL16_LO           R_PPC64 = 250 // R_POWERPC_REL16_LO
	R_PPC64_REL16_HI           R_PPC64 = 251 // R_POWERPC_REL16_HI
	R_PPC64_REL16_HA           R_PPC64 = 252 // R_POWERPC_REL16_HA
	R_PPC64_GNU_VTINHERIT      R_PPC64 = 253
	R_PPC64_GNU_VTENTRY        R_PPC64 = 254
)

(R_PPC64) GoString <- go1.5

1
func (i R_PPC64) GoString() string

(R_PPC64) String <- go1.5

1
func (i R_PPC64) String() string

type R_RISCV <- go1.11

1
type R_RISCV int

Relocation types for RISC-V processors.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
const (
	R_RISCV_NONE          R_RISCV = 0  /* No relocation. */
	R_RISCV_32            R_RISCV = 1  /* Add 32 bit zero extended symbol value */
	R_RISCV_64            R_RISCV = 2  /* Add 64 bit symbol value. */
	R_RISCV_RELATIVE      R_RISCV = 3  /* Add load address of shared object. */
	R_RISCV_COPY          R_RISCV = 4  /* Copy data from shared object. */
	R_RISCV_JUMP_SLOT     R_RISCV = 5  /* Set GOT entry to code address. */
	R_RISCV_TLS_DTPMOD32  R_RISCV = 6  /* 32 bit ID of module containing symbol */
	R_RISCV_TLS_DTPMOD64  R_RISCV = 7  /* ID of module containing symbol */
	R_RISCV_TLS_DTPREL32  R_RISCV = 8  /* 32 bit relative offset in TLS block */
	R_RISCV_TLS_DTPREL64  R_RISCV = 9  /* Relative offset in TLS block */
	R_RISCV_TLS_TPREL32   R_RISCV = 10 /* 32 bit relative offset in static TLS block */
	R_RISCV_TLS_TPREL64   R_RISCV = 11 /* Relative offset in static TLS block */
	R_RISCV_BRANCH        R_RISCV = 16 /* PC-relative branch */
	R_RISCV_JAL           R_RISCV = 17 /* PC-relative jump */
	R_RISCV_CALL          R_RISCV = 18 /* PC-relative call */
	R_RISCV_CALL_PLT      R_RISCV = 19 /* PC-relative call (PLT) */
	R_RISCV_GOT_HI20      R_RISCV = 20 /* PC-relative GOT reference */
	R_RISCV_TLS_GOT_HI20  R_RISCV = 21 /* PC-relative TLS IE GOT offset */
	R_RISCV_TLS_GD_HI20   R_RISCV = 22 /* PC-relative TLS GD reference */
	R_RISCV_PCREL_HI20    R_RISCV = 23 /* PC-relative reference */
	R_RISCV_PCREL_LO12_I  R_RISCV = 24 /* PC-relative reference */
	R_RISCV_PCREL_LO12_S  R_RISCV = 25 /* PC-relative reference */
	R_RISCV_HI20          R_RISCV = 26 /* Absolute address */
	R_RISCV_LO12_I        R_RISCV = 27 /* Absolute address */
	R_RISCV_LO12_S        R_RISCV = 28 /* Absolute address */
	R_RISCV_TPREL_HI20    R_RISCV = 29 /* TLS LE thread offset */
	R_RISCV_TPREL_LO12_I  R_RISCV = 30 /* TLS LE thread offset */
	R_RISCV_TPREL_LO12_S  R_RISCV = 31 /* TLS LE thread offset */
	R_RISCV_TPREL_ADD     R_RISCV = 32 /* TLS LE thread usage */
	R_RISCV_ADD8          R_RISCV = 33 /* 8-bit label addition */
	R_RISCV_ADD16         R_RISCV = 34 /* 16-bit label addition */
	R_RISCV_ADD32         R_RISCV = 35 /* 32-bit label addition */
	R_RISCV_ADD64         R_RISCV = 36 /* 64-bit label addition */
	R_RISCV_SUB8          R_RISCV = 37 /* 8-bit label subtraction */
	R_RISCV_SUB16         R_RISCV = 38 /* 16-bit label subtraction */
	R_RISCV_SUB32         R_RISCV = 39 /* 32-bit label subtraction */
	R_RISCV_SUB64         R_RISCV = 40 /* 64-bit label subtraction */
	R_RISCV_GNU_VTINHERIT R_RISCV = 41 /* GNU C++ vtable hierarchy */
	R_RISCV_GNU_VTENTRY   R_RISCV = 42 /* GNU C++ vtable member usage */
	R_RISCV_ALIGN         R_RISCV = 43 /* Alignment statement */
	R_RISCV_RVC_BRANCH    R_RISCV = 44 /* PC-relative branch offset */
	R_RISCV_RVC_JUMP      R_RISCV = 45 /* PC-relative jump offset */
	R_RISCV_RVC_LUI       R_RISCV = 46 /* Absolute address */
	R_RISCV_GPREL_I       R_RISCV = 47 /* GP-relative reference */
	R_RISCV_GPREL_S       R_RISCV = 48 /* GP-relative reference */
	R_RISCV_TPREL_I       R_RISCV = 49 /* TP-relative TLS LE load */
	R_RISCV_TPREL_S       R_RISCV = 50 /* TP-relative TLS LE store */
	R_RISCV_RELAX         R_RISCV = 51 /* Instruction pair can be relaxed */
	R_RISCV_SUB6          R_RISCV = 52 /* Local label subtraction */
	R_RISCV_SET6          R_RISCV = 53 /* Local label subtraction */
	R_RISCV_SET8          R_RISCV = 54 /* Local label subtraction */
	R_RISCV_SET16         R_RISCV = 55 /* Local label subtraction */
	R_RISCV_SET32         R_RISCV = 56 /* Local label subtraction */
	R_RISCV_32_PCREL      R_RISCV = 57 /* 32-bit PC relative */
)

(R_RISCV) GoString <- go1.11

1
func (i R_RISCV) GoString() string

(R_RISCV) String <- go1.11

1
func (i R_RISCV) String() string

type R_SPARC

1
type R_SPARC int

Relocation types for SPARC.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
const (
	R_SPARC_NONE     R_SPARC = 0
	R_SPARC_8        R_SPARC = 1
	R_SPARC_16       R_SPARC = 2
	R_SPARC_32       R_SPARC = 3
	R_SPARC_DISP8    R_SPARC = 4
	R_SPARC_DISP16   R_SPARC = 5
	R_SPARC_DISP32   R_SPARC = 6
	R_SPARC_WDISP30  R_SPARC = 7
	R_SPARC_WDISP22  R_SPARC = 8
	R_SPARC_HI22     R_SPARC = 9
	R_SPARC_22       R_SPARC = 10
	R_SPARC_13       R_SPARC = 11
	R_SPARC_LO10     R_SPARC = 12
	R_SPARC_GOT10    R_SPARC = 13
	R_SPARC_GOT13    R_SPARC = 14
	R_SPARC_GOT22    R_SPARC = 15
	R_SPARC_PC10     R_SPARC = 16
	R_SPARC_PC22     R_SPARC = 17
	R_SPARC_WPLT30   R_SPARC = 18
	R_SPARC_COPY     R_SPARC = 19
	R_SPARC_GLOB_DAT R_SPARC = 20
	R_SPARC_JMP_SLOT R_SPARC = 21
	R_SPARC_RELATIVE R_SPARC = 22
	R_SPARC_UA32     R_SPARC = 23
	R_SPARC_PLT32    R_SPARC = 24
	R_SPARC_HIPLT22  R_SPARC = 25
	R_SPARC_LOPLT10  R_SPARC = 26
	R_SPARC_PCPLT32  R_SPARC = 27
	R_SPARC_PCPLT22  R_SPARC = 28
	R_SPARC_PCPLT10  R_SPARC = 29
	R_SPARC_10       R_SPARC = 30
	R_SPARC_11       R_SPARC = 31
	R_SPARC_64       R_SPARC = 32
	R_SPARC_OLO10    R_SPARC = 33
	R_SPARC_HH22     R_SPARC = 34
	R_SPARC_HM10     R_SPARC = 35
	R_SPARC_LM22     R_SPARC = 36
	R_SPARC_PC_HH22  R_SPARC = 37
	R_SPARC_PC_HM10  R_SPARC = 38
	R_SPARC_PC_LM22  R_SPARC = 39
	R_SPARC_WDISP16  R_SPARC = 40
	R_SPARC_WDISP19  R_SPARC = 41
	R_SPARC_GLOB_JMP R_SPARC = 42
	R_SPARC_7        R_SPARC = 43
	R_SPARC_5        R_SPARC = 44
	R_SPARC_6        R_SPARC = 45
	R_SPARC_DISP64   R_SPARC = 46
	R_SPARC_PLT64    R_SPARC = 47
	R_SPARC_HIX22    R_SPARC = 48
	R_SPARC_LOX10    R_SPARC = 49
	R_SPARC_H44      R_SPARC = 50
	R_SPARC_M44      R_SPARC = 51
	R_SPARC_L44      R_SPARC = 52
	R_SPARC_REGISTER R_SPARC = 53
	R_SPARC_UA64     R_SPARC = 54
	R_SPARC_UA16     R_SPARC = 55
)

(R_SPARC) GoString

1
func (i R_SPARC) GoString() string

(R_SPARC) String

1
func (i R_SPARC) String() string

type R_X86_64

1
type R_X86_64 int

Relocation types for x86-64.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
const (
	R_X86_64_NONE            R_X86_64 = 0  /* No relocation. */
	R_X86_64_64              R_X86_64 = 1  /* Add 64 bit symbol value. */
	R_X86_64_PC32            R_X86_64 = 2  /* PC-relative 32 bit signed sym value. */
	R_X86_64_GOT32           R_X86_64 = 3  /* PC-relative 32 bit GOT offset. */
	R_X86_64_PLT32           R_X86_64 = 4  /* PC-relative 32 bit PLT offset. */
	R_X86_64_COPY            R_X86_64 = 5  /* Copy data from shared object. */
	R_X86_64_GLOB_DAT        R_X86_64 = 6  /* Set GOT entry to data address. */
	R_X86_64_JMP_SLOT        R_X86_64 = 7  /* Set GOT entry to code address. */
	R_X86_64_RELATIVE        R_X86_64 = 8  /* Add load address of shared object. */
	R_X86_64_GOTPCREL        R_X86_64 = 9  /* Add 32 bit signed pcrel offset to GOT. */
	R_X86_64_32              R_X86_64 = 10 /* Add 32 bit zero extended symbol value */
	R_X86_64_32S             R_X86_64 = 11 /* Add 32 bit sign extended symbol value */
	R_X86_64_16              R_X86_64 = 12 /* Add 16 bit zero extended symbol value */
	R_X86_64_PC16            R_X86_64 = 13 /* Add 16 bit signed extended pc relative symbol value */
	R_X86_64_8               R_X86_64 = 14 /* Add 8 bit zero extended symbol value */
	R_X86_64_PC8             R_X86_64 = 15 /* Add 8 bit signed extended pc relative symbol value */
	R_X86_64_DTPMOD64        R_X86_64 = 16 /* ID of module containing symbol */
	R_X86_64_DTPOFF64        R_X86_64 = 17 /* Offset in TLS block */
	R_X86_64_TPOFF64         R_X86_64 = 18 /* Offset in static TLS block */
	R_X86_64_TLSGD           R_X86_64 = 19 /* PC relative offset to GD GOT entry */
	R_X86_64_TLSLD           R_X86_64 = 20 /* PC relative offset to LD GOT entry */
	R_X86_64_DTPOFF32        R_X86_64 = 21 /* Offset in TLS block */
	R_X86_64_GOTTPOFF        R_X86_64 = 22 /* PC relative offset to IE GOT entry */
	R_X86_64_TPOFF32         R_X86_64 = 23 /* Offset in static TLS block */
	R_X86_64_PC64            R_X86_64 = 24 /* PC relative 64-bit sign extended symbol value. */
	R_X86_64_GOTOFF64        R_X86_64 = 25
	R_X86_64_GOTPC32         R_X86_64 = 26
	R_X86_64_GOT64           R_X86_64 = 27
	R_X86_64_GOTPCREL64      R_X86_64 = 28
	R_X86_64_GOTPC64         R_X86_64 = 29
	R_X86_64_GOTPLT64        R_X86_64 = 30
	R_X86_64_PLTOFF64        R_X86_64 = 31
	R_X86_64_SIZE32          R_X86_64 = 32
	R_X86_64_SIZE64          R_X86_64 = 33
	R_X86_64_GOTPC32_TLSDESC R_X86_64 = 34
	R_X86_64_TLSDESC_CALL    R_X86_64 = 35
	R_X86_64_TLSDESC         R_X86_64 = 36
	R_X86_64_IRELATIVE       R_X86_64 = 37
	R_X86_64_RELATIVE64      R_X86_64 = 38
	R_X86_64_PC32_BND        R_X86_64 = 39
	R_X86_64_PLT32_BND       R_X86_64 = 40
	R_X86_64_GOTPCRELX       R_X86_64 = 41
	R_X86_64_REX_GOTPCRELX   R_X86_64 = 42
)

(R_X86_64) GoString

1
func (i R_X86_64) GoString() string

(R_X86_64) String

1
func (i R_X86_64) String() string

type Rel32

1
2
3
4
type Rel32 struct {
	Off  uint32 /* Location to be relocated. */
	Info uint32 /* Relocation type and symbol index. */
}

ELF32 Relocations that don’t need an addend field.

type Rel64

1
2
3
4
type Rel64 struct {
	Off  uint64 /* Location to be relocated. */
	Info uint64 /* Relocation type and symbol index. */
}

ELF64 relocations that don’t need an addend field.

type Rela32

1
2
3
4
5
type Rela32 struct {
	Off    uint32 /* Location to be relocated. */
	Info   uint32 /* Relocation type and symbol index. */
	Addend int32  /* Addend. */
}

ELF32 Relocations that need an addend field.

type Rela64

1
2
3
4
5
type Rela64 struct {
	Off    uint64 /* Location to be relocated. */
	Info   uint64 /* Relocation type and symbol index. */
	Addend int64  /* Addend. */
}

ELF64 relocations that need an addend field.

type Section

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
type Section struct {
	SectionHeader

	// Embed ReaderAt for ReadAt method.
	// Do not embed SectionReader directly
	// to avoid having Read and Seek.
	// If a client wants Read and Seek it must use
	// Open() to avoid fighting over the seek offset
	// with other clients.
	//
	// ReaderAt may be nil if the section is not easily available
	// in a random-access form. For example, a compressed section
	// may have a nil ReaderAt.
	io.ReaderAt
	// contains filtered or unexported fields
}

A Section represents a single section in an ELF file.

(*Section) Data

1
func (s *Section) Data() ([]byte, error)

Data reads and returns the contents of the ELF section. Even if the section is stored compressed in the ELF file, Data returns uncompressed data.

For an SHT_NOBITS section, Data always returns a non-nil error.

(*Section) Open

1
func (s *Section) Open() io.ReadSeeker

Open returns a new ReadSeeker reading the ELF section. Even if the section is stored compressed in the ELF file, the ReadSeeker reads uncompressed data.

For an SHT_NOBITS section, all calls to the opened reader will return a non-nil error.

type Section32

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
type Section32 struct {
	Name      uint32 /* Section name (index into the section header string table). */
	Type      uint32 /* Section type. */
	Flags     uint32 /* Section flags. */
	Addr      uint32 /* Address in memory image. */
	Off       uint32 /* Offset in file. */
	Size      uint32 /* Size in bytes. */
	Link      uint32 /* Index of a related section. */
	Info      uint32 /* Depends on section type. */
	Addralign uint32 /* Alignment in bytes. */
	Entsize   uint32 /* Size of each entry in section. */
}

ELF32 Section header.

type Section64

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
type Section64 struct {
	Name      uint32 /* Section name (index into the section header string table). */
	Type      uint32 /* Section type. */
	Flags     uint64 /* Section flags. */
	Addr      uint64 /* Address in memory image. */
	Off       uint64 /* Offset in file. */
	Size      uint64 /* Size in bytes. */
	Link      uint32 /* Index of a related section. */
	Info      uint32 /* Depends on section type. */
	Addralign uint64 /* Alignment in bytes. */
	Entsize   uint64 /* Size of each entry in section. */
}

ELF64 Section header.

type SectionFlag

1
type SectionFlag uint32

Section flags.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
const (
	SHF_WRITE            SectionFlag = 0x1        /* Section contains writable data. */
	SHF_ALLOC            SectionFlag = 0x2        /* Section occupies memory. */
	SHF_EXECINSTR        SectionFlag = 0x4        /* Section contains instructions. */
	SHF_MERGE            SectionFlag = 0x10       /* Section may be merged. */
	SHF_STRINGS          SectionFlag = 0x20       /* Section contains strings. */
	SHF_INFO_LINK        SectionFlag = 0x40       /* sh_info holds section index. */
	SHF_LINK_ORDER       SectionFlag = 0x80       /* Special ordering requirements. */
	SHF_OS_NONCONFORMING SectionFlag = 0x100      /* OS-specific processing required. */
	SHF_GROUP            SectionFlag = 0x200      /* Member of section group. */
	SHF_TLS              SectionFlag = 0x400      /* Section contains TLS data. */
	SHF_COMPRESSED       SectionFlag = 0x800      /* Section is compressed. */
	SHF_MASKOS           SectionFlag = 0x0ff00000 /* OS-specific semantics. */
	SHF_MASKPROC         SectionFlag = 0xf0000000 /* Processor-specific semantics. */
)

(SectionFlag) GoString

1
func (i SectionFlag) GoString() string

(SectionFlag) String

1
func (i SectionFlag) String() string

type SectionHeader

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
type SectionHeader struct {
	Name      string
	Type      SectionType
	Flags     SectionFlag
	Addr      uint64
	Offset    uint64
	Size      uint64
	Link      uint32
	Info      uint32
	Addralign uint64
	Entsize   uint64

	// FileSize is the size of this section in the file in bytes.
	// If a section is compressed, FileSize is the size of the
	// compressed data, while Size (above) is the size of the
	// uncompressed data.
	FileSize uint64
}

A SectionHeader represents a single ELF section header.

type SectionIndex

1
type SectionIndex int

Special section indices.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
const (
	SHN_UNDEF     SectionIndex = 0      /* Undefined, missing, irrelevant. */
	SHN_LORESERVE SectionIndex = 0xff00 /* First of reserved range. */
	SHN_LOPROC    SectionIndex = 0xff00 /* First processor-specific. */
	SHN_HIPROC    SectionIndex = 0xff1f /* Last processor-specific. */
	SHN_LOOS      SectionIndex = 0xff20 /* First operating system-specific. */
	SHN_HIOS      SectionIndex = 0xff3f /* Last operating system-specific. */
	SHN_ABS       SectionIndex = 0xfff1 /* Absolute values. */
	SHN_COMMON    SectionIndex = 0xfff2 /* Common data. */
	SHN_XINDEX    SectionIndex = 0xffff /* Escape; index stored elsewhere. */
	SHN_HIRESERVE SectionIndex = 0xffff /* Last of reserved range. */
)

(SectionIndex) GoString

1
func (i SectionIndex) GoString() string

(SectionIndex) String

1
func (i SectionIndex) String() string

type SectionType

1
type SectionType uint32

Section type.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
const (
	SHT_NULL           SectionType = 0          /* inactive */
	SHT_PROGBITS       SectionType = 1          /* program defined information */
	SHT_SYMTAB         SectionType = 2          /* symbol table section */
	SHT_STRTAB         SectionType = 3          /* string table section */
	SHT_RELA           SectionType = 4          /* relocation section with addends */
	SHT_HASH           SectionType = 5          /* symbol hash table section */
	SHT_DYNAMIC        SectionType = 6          /* dynamic section */
	SHT_NOTE           SectionType = 7          /* note section */
	SHT_NOBITS         SectionType = 8          /* no space section */
	SHT_REL            SectionType = 9          /* relocation section - no addends */
	SHT_SHLIB          SectionType = 10         /* reserved - purpose unknown */
	SHT_DYNSYM         SectionType = 11         /* dynamic symbol table section */
	SHT_INIT_ARRAY     SectionType = 14         /* Initialization function pointers. */
	SHT_FINI_ARRAY     SectionType = 15         /* Termination function pointers. */
	SHT_PREINIT_ARRAY  SectionType = 16         /* Pre-initialization function ptrs. */
	SHT_GROUP          SectionType = 17         /* Section group. */
	SHT_SYMTAB_SHNDX   SectionType = 18         /* Section indexes (see SHN_XINDEX). */
	SHT_LOOS           SectionType = 0x60000000 /* First of OS specific semantics */
	SHT_GNU_ATTRIBUTES SectionType = 0x6ffffff5 /* GNU object attributes */
	SHT_GNU_HASH       SectionType = 0x6ffffff6 /* GNU hash table */
	SHT_GNU_LIBLIST    SectionType = 0x6ffffff7 /* GNU prelink library list */
	SHT_GNU_VERDEF     SectionType = 0x6ffffffd /* GNU version definition section */
	SHT_GNU_VERNEED    SectionType = 0x6ffffffe /* GNU version needs section */
	SHT_GNU_VERSYM     SectionType = 0x6fffffff /* GNU version symbol table */
	SHT_HIOS           SectionType = 0x6fffffff /* Last of OS specific semantics */
	SHT_LOPROC         SectionType = 0x70000000 /* reserved range for processor */
	SHT_MIPS_ABIFLAGS  SectionType = 0x7000002a /* .MIPS.abiflags */
	SHT_HIPROC         SectionType = 0x7fffffff /* specific section header types */
	SHT_LOUSER         SectionType = 0x80000000 /* reserved range for application */
	SHT_HIUSER         SectionType = 0xffffffff /* specific indexes */
)

(SectionType) GoString

1
func (i SectionType) GoString() string

(SectionType) String

1
func (i SectionType) String() string

type Sym32

1
2
3
4
5
6
7
8
type Sym32 struct {
	Name  uint32
	Value uint32
	Size  uint32
	Info  uint8
	Other uint8
	Shndx uint16
}

ELF32 Symbol.

type Sym64

1
2
3
4
5
6
7
8
type Sym64 struct {
	Name  uint32 /* String table index of name. */
	Info  uint8  /* Type and binding information. */
	Other uint8  /* Reserved (not used). */
	Shndx uint16 /* Section index of symbol. */
	Value uint64 /* Symbol value. */
	Size  uint64 /* Size of associated object. */
}

ELF64 symbol table entries.

type SymBind

1
type SymBind int

Symbol Binding - ELFNN_ST_BIND - st_info

1
2
3
4
5
6
7
8
9
const (
	STB_LOCAL  SymBind = 0  /* Local symbol */
	STB_GLOBAL SymBind = 1  /* Global symbol */
	STB_WEAK   SymBind = 2  /* like global - lower precedence */
	STB_LOOS   SymBind = 10 /* Reserved range for operating system */
	STB_HIOS   SymBind = 12 /*   specific semantics. */
	STB_LOPROC SymBind = 13 /* reserved range for processor */
	STB_HIPROC SymBind = 15 /*   specific semantics. */
)

func ST_BIND

1
func ST_BIND(info uint8) SymBind

(SymBind) GoString

1
func (i SymBind) GoString() string

(SymBind) String

1
func (i SymBind) String() string

type SymType

1
type SymType int

Symbol type - ELFNN_ST_TYPE - st_info

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
const (
	STT_NOTYPE  SymType = 0  /* Unspecified type. */
	STT_OBJECT  SymType = 1  /* Data object. */
	STT_FUNC    SymType = 2  /* Function. */
	STT_SECTION SymType = 3  /* Section. */
	STT_FILE    SymType = 4  /* Source file. */
	STT_COMMON  SymType = 5  /* Uninitialized common block. */
	STT_TLS     SymType = 6  /* TLS object. */
	STT_LOOS    SymType = 10 /* Reserved range for operating system */
	STT_HIOS    SymType = 12 /*   specific semantics. */
	STT_LOPROC  SymType = 13 /* reserved range for processor */
	STT_HIPROC  SymType = 15 /*   specific semantics. */
)

func ST_TYPE

1
func ST_TYPE(info uint8) SymType

(SymType) GoString

1
func (i SymType) GoString() string

(SymType) String

1
func (i SymType) String() string

type SymVis

1
type SymVis int

Symbol visibility - ELFNN_ST_VISIBILITY - st_other

1
2
3
4
5
6
const (
	STV_DEFAULT   SymVis = 0x0 /* Default visibility (see binding). */
	STV_INTERNAL  SymVis = 0x1 /* Special meaning in relocatable objects. */
	STV_HIDDEN    SymVis = 0x2 /* Not visible. */
	STV_PROTECTED SymVis = 0x3 /* Visible but not preemptible. */
)

func ST_VISIBILITY

1
func ST_VISIBILITY(other uint8) SymVis

(SymVis) GoString

1
func (i SymVis) GoString() string

(SymVis) String

1
func (i SymVis) String() string

type Symbol

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
type Symbol struct {
	Name        string
	Info, Other byte
	Section     SectionIndex
	Value, Size uint64

	// Version and Library are present only for the dynamic symbol
	// table.
	Version string
	Library string
}

A Symbol represents an entry in an ELF symbol table section.

type Type

1
type Type uint16

Type is found in Header.Type.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
const (
	ET_NONE   Type = 0      /* Unknown type. */
	ET_REL    Type = 1      /* Relocatable. */
	ET_EXEC   Type = 2      /* Executable. */
	ET_DYN    Type = 3      /* Shared object. */
	ET_CORE   Type = 4      /* Core file. */
	ET_LOOS   Type = 0xfe00 /* First operating system specific. */
	ET_HIOS   Type = 0xfeff /* Last operating system-specific. */
	ET_LOPROC Type = 0xff00 /* First processor-specific. */
	ET_HIPROC Type = 0xffff /* Last processor-specific. */
)

(Type) GoString

1
func (i Type) GoString() string

(Type) String

1
func (i Type) String() string

type Version

1
type Version byte

Version is found in Header.Ident[EI_VERSION] and Header.Version.

1
2
3
4
const (
	EV_NONE    Version = 0
	EV_CURRENT Version = 1
)

(Version) GoString

1
func (i Version) GoString() string

(Version) String

1
func (i Version) String() string

6.4 - gosym

gosym

https://pkg.go.dev/debug/gosym@go1.20.1

Package gosym implements access to the Go symbol and line number tables embedded in Go binaries generated by the gc compilers.

常量

This section is empty.

变量

This section is empty.

函数

This section is empty.

类型

type DecodingError

1
2
3
type DecodingError struct {
	// contains filtered or unexported fields
}

DecodingError represents an error during the decoding of the symbol table.

(*DecodingError) Error

1
func (e *DecodingError) Error() string

type Func

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
type Func struct {
	Entry uint64
	*Sym
	End       uint64
	Params    []*Sym // nil for Go 1.3 and later binaries
	Locals    []*Sym // nil for Go 1.3 and later binaries
	FrameSize int
	LineTable *LineTable
	Obj       *Obj
}

A Func collects information about a single function.

type LineTable

1
2
3
4
5
6
type LineTable struct {
	Data []byte
	PC   uint64
	Line int
	// contains filtered or unexported fields
}

A LineTable is a data structure mapping program counters to line numbers.

In Go 1.1 and earlier, each function (represented by a Func) had its own LineTable, and the line number corresponded to a numbering of all source lines in the program, across all files. That absolute line number would then have to be converted separately to a file name and line number within the file.

In Go 1.2, the format of the data changed so that there is a single LineTable for the entire program, shared by all Funcs, and there are no absolute line numbers, just line numbers within specific files.

For the most part, LineTable’s methods should be treated as an internal detail of the package; callers should use the methods on Table instead.

func NewLineTable

1
func NewLineTable(data []byte, text uint64) *LineTable

NewLineTable returns a new PC/line table corresponding to the encoded data. Text must be the start address of the corresponding text segment.

Example
Example

type Obj

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
type Obj struct {
	// Funcs is a list of functions in the Obj.
	Funcs []Func

	// In Go 1.1 and earlier, Paths is a list of symbols corresponding
	// to the source file names that produced the Obj.
	// In Go 1.2, Paths is nil.
	// Use the keys of Table.Files to obtain a list of source files.
	Paths []Sym // meta
}

An Obj represents a collection of functions in a symbol table.

The exact method of division of a binary into separate Objs is an internal detail of the symbol table format.

In early versions of Go each source file became a different Obj.

In Go 1 and Go 1.1, each package produced one Obj for all Go sources and one Obj per C source file.

In Go 1.2, there is a single Obj for the entire program.

type Sym

1
2
3
4
5
6
7
8
9
type Sym struct {
	Value  uint64
	Type   byte
	Name   string
	GoType uint64
	// If this symbol is a function symbol, the corresponding Func
	Func *Func
	// contains filtered or unexported fields
}

A Sym represents a single symbol table entry.

(*Sym) BaseName

1
func (s *Sym) BaseName() string

BaseName returns the symbol name without the package or receiver name.

(*Sym) PackageName

1
func (s *Sym) PackageName() string

PackageName returns the package part of the symbol name, or the empty string if there is none.

(*Sym) ReceiverName

1
func (s *Sym) ReceiverName() string

ReceiverName returns the receiver type name of this symbol, or the empty string if there is none. A receiver name is only detected in the case that s.Name is fully-specified with a package name.

(*Sym) Static

1
func (s *Sym) Static() bool

Static reports whether this symbol is static (not visible outside its file).

type Table

1
2
3
4
5
6
7
type Table struct {
	Syms  []Sym // nil for Go 1.3 and later binaries
	Funcs []Func
	Files map[string]*Obj // for Go 1.2 and later all files map to one Obj
	Objs  []Obj           // for Go 1.2 and later only one Obj in slice
	// contains filtered or unexported fields
}

Table represents a Go symbol table. It stores all of the symbols decoded from the program and provides methods to translate between symbols, names, and addresses.

func NewTable

1
func NewTable(symtab []byte, pcln *LineTable) (*Table, error)

NewTable decodes the Go symbol table (the “.gosymtab” section in ELF), returning an in-memory representation. Starting with Go 1.3, the Go symbol table no longer includes symbol data.

(*Table) LineToPC

1
func (t *Table) LineToPC(file string, line int) (pc uint64, fn *Func, err error)

LineToPC looks up the first program counter on the given line in the named file. It returns UnknownPathError or UnknownLineError if there is an error looking up this line.

(*Table) LookupFunc

1
func (t *Table) LookupFunc(name string) *Func

LookupFunc returns the text, data, or bss symbol with the given name, or nil if no such symbol is found.

(*Table) LookupSym

1
func (t *Table) LookupSym(name string) *Sym

LookupSym returns the text, data, or bss symbol with the given name, or nil if no such symbol is found.

(*Table) PCToFunc

1
func (t *Table) PCToFunc(pc uint64) *Func

PCToFunc returns the function containing the program counter pc, or nil if there is no such function.

(*Table) PCToLine

1
func (t *Table) PCToLine(pc uint64) (file string, line int, fn *Func)

PCToLine looks up line number information for a program counter. If there is no information, it returns fn == nil.

(*Table) SymByAddr

1
func (t *Table) SymByAddr(addr uint64) *Sym

SymByAddr returns the text, data, or bss symbol starting at the given address.

type UnknownFileError

1
type UnknownFileError string

UnknownFileError represents a failure to find the specific file in the symbol table.

(UnknownFileError) Error

1
func (e UnknownFileError) Error() string

type UnknownLineError

1
2
3
4
type UnknownLineError struct {
	File string
	Line int
}

UnknownLineError represents a failure to map a line to a program counter, either because the line is beyond the bounds of the file or because there is no code on the given line.

(*UnknownLineError) Error

1
func (e *UnknownLineError) Error() string

6.5 - macho

macho

https://pkg.go.dev/debug/macho@go1.20.1

Package macho implements access to Mach-O object files.

Security

This package is not designed to be hardened against adversarial inputs, and is outside the scope of https://go.dev/security/policy. In particular, only basic validation is done when parsing object files. As such, care should be taken when parsing untrusted inputs, as parsing malformed files may consume significant resources, or cause panics.

常量

View Source

1
2
3
4
5
const (
	Magic32  uint32 = 0xfeedface
	Magic64  uint32 = 0xfeedfacf
	MagicFat uint32 = 0xcafebabe
)

View Source

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
const (
	FlagNoUndefs              uint32 = 0x1
	FlagIncrLink              uint32 = 0x2
	FlagDyldLink              uint32 = 0x4
	FlagBindAtLoad            uint32 = 0x8
	FlagPrebound              uint32 = 0x10
	FlagSplitSegs             uint32 = 0x20
	FlagLazyInit              uint32 = 0x40
	FlagTwoLevel              uint32 = 0x80
	FlagForceFlat             uint32 = 0x100
	FlagNoMultiDefs           uint32 = 0x200
	FlagNoFixPrebinding       uint32 = 0x400
	FlagPrebindable           uint32 = 0x800
	FlagAllModsBound          uint32 = 0x1000
	FlagSubsectionsViaSymbols uint32 = 0x2000
	FlagCanonical             uint32 = 0x4000
	FlagWeakDefines           uint32 = 0x8000
	FlagBindsToWeak           uint32 = 0x10000
	FlagAllowStackExecution   uint32 = 0x20000
	FlagRootSafe              uint32 = 0x40000
	FlagSetuidSafe            uint32 = 0x80000
	FlagNoReexportedDylibs    uint32 = 0x100000
	FlagPIE                   uint32 = 0x200000
	FlagDeadStrippableDylib   uint32 = 0x400000
	FlagHasTLVDescriptors     uint32 = 0x800000
	FlagNoHeapExecution       uint32 = 0x1000000
	FlagAppExtensionSafe      uint32 = 0x2000000
)

变量

View Source

1
var ErrNotFat = &FormatError{0, "not a fat Mach-O file", nil}

ErrNotFat is returned from NewFatFile or OpenFat when the file is not a universal binary but may be a thin binary, based on its magic number.

函数

This section is empty.

类型

type Cpu

1
type Cpu uint32

A Cpu is a Mach-O cpu type.

1
2
3
4
5
6
7
8
const (
	Cpu386   Cpu = 7
	CpuAmd64 Cpu = Cpu386 | cpuArch64
	CpuArm   Cpu = 12
	CpuArm64 Cpu = CpuArm | cpuArch64
	CpuPpc   Cpu = 18
	CpuPpc64 Cpu = CpuPpc | cpuArch64
)

(Cpu) GoString

1
func (i Cpu) GoString() string

(Cpu) String

1
func (i Cpu) String() string

type Dylib

1
2
3
4
5
6
7
type Dylib struct {
	LoadBytes
	Name           string
	Time           uint32
	CurrentVersion uint32
	CompatVersion  uint32
}

A Dylib represents a Mach-O load dynamic library command.

type DylibCmd

1
2
3
4
5
6
7
8
type DylibCmd struct {
	Cmd            LoadCmd
	Len            uint32
	Name           uint32
	Time           uint32
	CurrentVersion uint32
	CompatVersion  uint32
}

A DylibCmd is a Mach-O load dynamic library command.

type Dysymtab

1
2
3
4
5
type Dysymtab struct {
	LoadBytes
	DysymtabCmd
	IndirectSyms []uint32 // indices into Symtab.Syms
}

A Dysymtab represents a Mach-O dynamic symbol table command.

type DysymtabCmd

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
type DysymtabCmd struct {
	Cmd            LoadCmd
	Len            uint32
	Ilocalsym      uint32
	Nlocalsym      uint32
	Iextdefsym     uint32
	Nextdefsym     uint32
	Iundefsym      uint32
	Nundefsym      uint32
	Tocoffset      uint32
	Ntoc           uint32
	Modtaboff      uint32
	Nmodtab        uint32
	Extrefsymoff   uint32
	Nextrefsyms    uint32
	Indirectsymoff uint32
	Nindirectsyms  uint32
	Extreloff      uint32
	Nextrel        uint32
	Locreloff      uint32
	Nlocrel        uint32
}

A DysymtabCmd is a Mach-O dynamic symbol table command.

type FatArch <- go1.3

1
2
3
4
type FatArch struct {
	FatArchHeader
	*File
}

A FatArch is a Mach-O File inside a FatFile.

type FatArchHeader <- go1.3

1
2
3
4
5
6
7
type FatArchHeader struct {
	Cpu    Cpu
	SubCpu uint32
	Offset uint32
	Size   uint32
	Align  uint32
}

A FatArchHeader represents a fat header for a specific image architecture.

type FatFile <- go1.3

1
2
3
4
5
type FatFile struct {
	Magic  uint32
	Arches []FatArch
	// contains filtered or unexported fields
}

A FatFile is a Mach-O universal binary that contains at least one architecture.

func NewFatFile <- go1.3

1
func NewFatFile(r io.ReaderAt) (*FatFile, error)

NewFatFile creates a new FatFile for accessing all the Mach-O images in a universal binary. The Mach-O binary is expected to start at position 0 in the ReaderAt.

func OpenFat <- go1.3

1
func OpenFat(name string) (*FatFile, error)

OpenFat opens the named file using os.Open and prepares it for use as a Mach-O universal binary.

(*FatFile) Close <- go1.3

1
func (ff *FatFile) Close() error

type File

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
type File struct {
	FileHeader
	ByteOrder binary.ByteOrder
	Loads     []Load
	Sections  []*Section

	Symtab   *Symtab
	Dysymtab *Dysymtab
	// contains filtered or unexported fields
}

A File represents an open Mach-O file.

func NewFile

1
func NewFile(r io.ReaderAt) (*File, error)

NewFile creates a new File for accessing a Mach-O binary in an underlying reader. The Mach-O binary is expected to start at position 0 in the ReaderAt.

func Open

1
func Open(name string) (*File, error)

Open opens the named file using os.Open and prepares it for use as a Mach-O binary.

(*File) Close

1
func (f *File) Close() error

Close closes the File. If the File was created using NewFile directly instead of Open, Close has no effect.

(*File) DWARF

1
func (f *File) DWARF() (*dwarf.Data, error)

DWARF returns the DWARF debug information for the Mach-O file.

(*File) ImportedLibraries

1
func (f *File) ImportedLibraries() ([]string, error)

ImportedLibraries returns the paths of all libraries referred to by the binary f that are expected to be linked with the binary at dynamic link time.

(*File) ImportedSymbols

1
func (f *File) ImportedSymbols() ([]string, error)

ImportedSymbols returns the names of all symbols referred to by the binary f that are expected to be satisfied by other libraries at dynamic load time.

(*File) Section

1
func (f *File) Section(name string) *Section

Section returns the first section with the given name, or nil if no such section exists.

(*File) Segment

1
func (f *File) Segment(name string) *Segment

Segment returns the first Segment with the given name, or nil if no such segment exists.

type FileHeader

1
2
3
4
5
6
7
8
9
type FileHeader struct {
	Magic  uint32
	Cpu    Cpu
	SubCpu uint32
	Type   Type
	Ncmd   uint32
	Cmdsz  uint32
	Flags  uint32
}

A FileHeader represents a Mach-O file header.

type FormatError

1
2
3
type FormatError struct {
	// contains filtered or unexported fields
}

FormatError is returned by some operations if the data does not have the correct format for an object file.

(*FormatError) Error

1
func (e *FormatError) Error() string

type Load

1
2
3
type Load interface {
	Raw() []byte
}

A Load represents any Mach-O load command.

type LoadBytes

1
type LoadBytes []byte

A LoadBytes is the uninterpreted bytes of a Mach-O load command.

(LoadBytes) Raw

1
func (b LoadBytes) Raw() []byte

type LoadCmd

1
type LoadCmd uint32

A LoadCmd is a Mach-O load command.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
const (
	LoadCmdSegment    LoadCmd = 0x1
	LoadCmdSymtab     LoadCmd = 0x2
	LoadCmdThread     LoadCmd = 0x4
	LoadCmdUnixThread LoadCmd = 0x5 // thread+stack
	LoadCmdDysymtab   LoadCmd = 0xb
	LoadCmdDylib      LoadCmd = 0xc // load dylib command
	LoadCmdDylinker   LoadCmd = 0xf // id dylinker command (not load dylinker command)
	LoadCmdSegment64  LoadCmd = 0x19
	LoadCmdRpath      LoadCmd = 0x8000001c
)

(LoadCmd) GoString

1
func (i LoadCmd) GoString() string

(LoadCmd) String

1
func (i LoadCmd) String() string

type Nlist32

1
2
3
4
5
6
7
type Nlist32 struct {
	Name  uint32
	Type  uint8
	Sect  uint8
	Desc  uint16
	Value uint32
}

An Nlist32 is a Mach-O 32-bit symbol table entry.

type Nlist64

1
2
3
4
5
6
7
type Nlist64 struct {
	Name  uint32
	Type  uint8
	Sect  uint8
	Desc  uint16
	Value uint64
}

An Nlist64 is a Mach-O 64-bit symbol table entry.

type Regs386

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
type Regs386 struct {
	AX    uint32
	BX    uint32
	CX    uint32
	DX    uint32
	DI    uint32
	SI    uint32
	BP    uint32
	SP    uint32
	SS    uint32
	FLAGS uint32
	IP    uint32
	CS    uint32
	DS    uint32
	ES    uint32
	FS    uint32
	GS    uint32
}

Regs386 is the Mach-O 386 register structure.

type RegsAMD64

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
type RegsAMD64 struct {
	AX    uint64
	BX    uint64
	CX    uint64
	DX    uint64
	DI    uint64
	SI    uint64
	BP    uint64
	SP    uint64
	R8    uint64
	R9    uint64
	R10   uint64
	R11   uint64
	R12   uint64
	R13   uint64
	R14   uint64
	R15   uint64
	IP    uint64
	FLAGS uint64
	CS    uint64
	FS    uint64
	GS    uint64
}

RegsAMD64 is the Mach-O AMD64 register structure.

type Reloc <- go1.10

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
type Reloc struct {
	Addr  uint32
	Value uint32
	// when Scattered == false && Extern == true, Value is the symbol number.
	// when Scattered == false && Extern == false, Value is the section number.
	// when Scattered == true, Value is the value that this reloc refers to.
	Type      uint8
	Len       uint8 // 0=byte, 1=word, 2=long, 3=quad
	Pcrel     bool
	Extern    bool // valid if Scattered == false
	Scattered bool
}

A Reloc represents a Mach-O relocation.

type RelocTypeARM <- go1.10

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
type RelocTypeARM int
const (
	ARM_RELOC_VANILLA        RelocTypeARM = 0
	ARM_RELOC_PAIR           RelocTypeARM = 1
	ARM_RELOC_SECTDIFF       RelocTypeARM = 2
	ARM_RELOC_LOCAL_SECTDIFF RelocTypeARM = 3
	ARM_RELOC_PB_LA_PTR      RelocTypeARM = 4
	ARM_RELOC_BR24           RelocTypeARM = 5
	ARM_THUMB_RELOC_BR22     RelocTypeARM = 6
	ARM_THUMB_32BIT_BRANCH   RelocTypeARM = 7
	ARM_RELOC_HALF           RelocTypeARM = 8
	ARM_RELOC_HALF_SECTDIFF  RelocTypeARM = 9
)

(RelocTypeARM) GoString <- go1.10

1
func (r RelocTypeARM) GoString() string

(RelocTypeARM) String <- go1.10

1
func (i RelocTypeARM) String() string

type RelocTypeARM64 <- go1.10

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
type RelocTypeARM64 int
const (
	ARM64_RELOC_UNSIGNED            RelocTypeARM64 = 0
	ARM64_RELOC_SUBTRACTOR          RelocTypeARM64 = 1
	ARM64_RELOC_BRANCH26            RelocTypeARM64 = 2
	ARM64_RELOC_PAGE21              RelocTypeARM64 = 3
	ARM64_RELOC_PAGEOFF12           RelocTypeARM64 = 4
	ARM64_RELOC_GOT_LOAD_PAGE21     RelocTypeARM64 = 5
	ARM64_RELOC_GOT_LOAD_PAGEOFF12  RelocTypeARM64 = 6
	ARM64_RELOC_POINTER_TO_GOT      RelocTypeARM64 = 7
	ARM64_RELOC_TLVP_LOAD_PAGE21    RelocTypeARM64 = 8
	ARM64_RELOC_TLVP_LOAD_PAGEOFF12 RelocTypeARM64 = 9
	ARM64_RELOC_ADDEND              RelocTypeARM64 = 10
)

(RelocTypeARM64) GoString <- go1.10

1
func (r RelocTypeARM64) GoString() string

(RelocTypeARM64) String <- go1.10

1
func (i RelocTypeARM64) String() string

type RelocTypeGeneric <- go1.10

1
2
3
4
5
6
7
8
9
type RelocTypeGeneric int
const (
	GENERIC_RELOC_VANILLA        RelocTypeGeneric = 0
	GENERIC_RELOC_PAIR           RelocTypeGeneric = 1
	GENERIC_RELOC_SECTDIFF       RelocTypeGeneric = 2
	GENERIC_RELOC_PB_LA_PTR      RelocTypeGeneric = 3
	GENERIC_RELOC_LOCAL_SECTDIFF RelocTypeGeneric = 4
	GENERIC_RELOC_TLV            RelocTypeGeneric = 5
)

(RelocTypeGeneric) GoString <- go1.10

1
func (r RelocTypeGeneric) GoString() string

(RelocTypeGeneric) String <- go1.10

1
func (i RelocTypeGeneric) String() string

type RelocTypeX86_64 <- go1.10

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
type RelocTypeX86_64 int
const (
	X86_64_RELOC_UNSIGNED   RelocTypeX86_64 = 0
	X86_64_RELOC_SIGNED     RelocTypeX86_64 = 1
	X86_64_RELOC_BRANCH     RelocTypeX86_64 = 2
	X86_64_RELOC_GOT_LOAD   RelocTypeX86_64 = 3
	X86_64_RELOC_GOT        RelocTypeX86_64 = 4
	X86_64_RELOC_SUBTRACTOR RelocTypeX86_64 = 5
	X86_64_RELOC_SIGNED_1   RelocTypeX86_64 = 6
	X86_64_RELOC_SIGNED_2   RelocTypeX86_64 = 7
	X86_64_RELOC_SIGNED_4   RelocTypeX86_64 = 8
	X86_64_RELOC_TLV        RelocTypeX86_64 = 9
)

(RelocTypeX86_64) GoString <- go1.10

1
func (r RelocTypeX86_64) GoString() string

(RelocTypeX86_64) String <- go1.10

1
func (i RelocTypeX86_64) String() string

type Rpath <- go1.10

1
2
3
4
type Rpath struct {
	LoadBytes
	Path string
}

A Rpath represents a Mach-O rpath command.

type RpathCmd <- go1.10

1
2
3
4
5
type RpathCmd struct {
	Cmd  LoadCmd
	Len  uint32
	Path uint32
}

A RpathCmd is a Mach-O rpath command.

type Section

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
type Section struct {
	SectionHeader
	Relocs []Reloc

	// Embed ReaderAt for ReadAt method.
	// Do not embed SectionReader directly
	// to avoid having Read and Seek.
	// If a client wants Read and Seek it must use
	// Open() to avoid fighting over the seek offset
	// with other clients.
	io.ReaderAt
	// contains filtered or unexported fields
}

(*Section) Data

1
func (s *Section) Data() ([]byte, error)

Data reads and returns the contents of the Mach-O section.

(*Section) Open

1
func (s *Section) Open() io.ReadSeeker

Open returns a new ReadSeeker reading the Mach-O section.

type Section32

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
type Section32 struct {
	Name     [16]byte
	Seg      [16]byte
	Addr     uint32
	Size     uint32
	Offset   uint32
	Align    uint32
	Reloff   uint32
	Nreloc   uint32
	Flags    uint32
	Reserve1 uint32
	Reserve2 uint32
}

A Section32 is a 32-bit Mach-O section header.

type Section64

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
type Section64 struct {
	Name     [16]byte
	Seg      [16]byte
	Addr     uint64
	Size     uint64
	Offset   uint32
	Align    uint32
	Reloff   uint32
	Nreloc   uint32
	Flags    uint32
	Reserve1 uint32
	Reserve2 uint32
	Reserve3 uint32
}

A Section64 is a 64-bit Mach-O section header.

type SectionHeader

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
type SectionHeader struct {
	Name   string
	Seg    string
	Addr   uint64
	Size   uint64
	Offset uint32
	Align  uint32
	Reloff uint32
	Nreloc uint32
	Flags  uint32
}

type Segment

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
type Segment struct {
	LoadBytes
	SegmentHeader

	// Embed ReaderAt for ReadAt method.
	// Do not embed SectionReader directly
	// to avoid having Read and Seek.
	// If a client wants Read and Seek it must use
	// Open() to avoid fighting over the seek offset
	// with other clients.
	io.ReaderAt
	// contains filtered or unexported fields
}

A Segment represents a Mach-O 32-bit or 64-bit load segment command.

(*Segment) Data

1
func (s *Segment) Data() ([]byte, error)

Data reads and returns the contents of the segment.

(*Segment) Open

1
func (s *Segment) Open() io.ReadSeeker

Open returns a new ReadSeeker reading the segment.

type Segment32

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
type Segment32 struct {
	Cmd     LoadCmd
	Len     uint32
	Name    [16]byte
	Addr    uint32
	Memsz   uint32
	Offset  uint32
	Filesz  uint32
	Maxprot uint32
	Prot    uint32
	Nsect   uint32
	Flag    uint32
}

A Segment32 is a 32-bit Mach-O segment load command.

type Segment64

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
type Segment64 struct {
	Cmd     LoadCmd
	Len     uint32
	Name    [16]byte
	Addr    uint64
	Memsz   uint64
	Offset  uint64
	Filesz  uint64
	Maxprot uint32
	Prot    uint32
	Nsect   uint32
	Flag    uint32
}

A Segment64 is a 64-bit Mach-O segment load command.

type SegmentHeader

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
type SegmentHeader struct {
	Cmd     LoadCmd
	Len     uint32
	Name    string
	Addr    uint64
	Memsz   uint64
	Offset  uint64
	Filesz  uint64
	Maxprot uint32
	Prot    uint32
	Nsect   uint32
	Flag    uint32
}

A SegmentHeader is the header for a Mach-O 32-bit or 64-bit load segment command.

type Symbol

1
2
3
4
5
6
7
type Symbol struct {
	Name  string
	Type  uint8
	Sect  uint8
	Desc  uint16
	Value uint64
}

A Symbol is a Mach-O 32-bit or 64-bit symbol table entry.

type Symtab

1
2
3
4
5
type Symtab struct {
	LoadBytes
	SymtabCmd
	Syms []Symbol
}

A Symtab represents a Mach-O symbol table command.

type SymtabCmd

1
2
3
4
5
6
7
8
type SymtabCmd struct {
	Cmd     LoadCmd
	Len     uint32
	Symoff  uint32
	Nsyms   uint32
	Stroff  uint32
	Strsize uint32
}

A SymtabCmd is a Mach-O symbol table command.

type Thread

1
2
3
4
5
6
type Thread struct {
	Cmd  LoadCmd
	Len  uint32
	Type uint32
	Data []uint32
}

A Thread is a Mach-O thread state command.

type Type

1
type Type uint32

A Type is the Mach-O file type, e.g. an object file, executable, or dynamic library.

1
2
3
4
5
6
const (
	TypeObj    Type = 1
	TypeExec   Type = 2
	TypeDylib  Type = 6
	TypeBundle Type = 8
)

(Type) GoString <- go1.10

1
func (t Type) GoString() string

(Type) String <- go1.10

1
func (t Type) String() string

6.6 - pe

pe

https://pkg.go.dev/debug/pe@go1.20.1

Package pe implements access to PE (Microsoft Windows Portable Executable) files.

Security

This package is not designed to be hardened against adversarial inputs, and is outside the scope of https://go.dev/security/policy. In particular, only basic validation is done when parsing object files. As such, care should be taken when parsing untrusted inputs, as parsing malformed files may consume significant resources, or cause panics.

常量

View Source

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
const (
	IMAGE_FILE_MACHINE_UNKNOWN     = 0x0
	IMAGE_FILE_MACHINE_AM33        = 0x1d3
	IMAGE_FILE_MACHINE_AMD64       = 0x8664
	IMAGE_FILE_MACHINE_ARM         = 0x1c0
	IMAGE_FILE_MACHINE_ARMNT       = 0x1c4
	IMAGE_FILE_MACHINE_ARM64       = 0xaa64
	IMAGE_FILE_MACHINE_EBC         = 0xebc
	IMAGE_FILE_MACHINE_I386        = 0x14c
	IMAGE_FILE_MACHINE_IA64        = 0x200
	IMAGE_FILE_MACHINE_LOONGARCH32 = 0x6232
	IMAGE_FILE_MACHINE_LOONGARCH64 = 0x6264
	IMAGE_FILE_MACHINE_M32R        = 0x9041
	IMAGE_FILE_MACHINE_MIPS16      = 0x266
	IMAGE_FILE_MACHINE_MIPSFPU     = 0x366
	IMAGE_FILE_MACHINE_MIPSFPU16   = 0x466
	IMAGE_FILE_MACHINE_POWERPC     = 0x1f0
	IMAGE_FILE_MACHINE_POWERPCFP   = 0x1f1
	IMAGE_FILE_MACHINE_R4000       = 0x166
	IMAGE_FILE_MACHINE_SH3         = 0x1a2
	IMAGE_FILE_MACHINE_SH3DSP      = 0x1a3
	IMAGE_FILE_MACHINE_SH4         = 0x1a6
	IMAGE_FILE_MACHINE_SH5         = 0x1a8
	IMAGE_FILE_MACHINE_THUMB       = 0x1c2
	IMAGE_FILE_MACHINE_WCEMIPSV2   = 0x169
	IMAGE_FILE_MACHINE_RISCV32     = 0x5032
	IMAGE_FILE_MACHINE_RISCV64     = 0x5064
	IMAGE_FILE_MACHINE_RISCV128    = 0x5128
)

View Source

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
const (
	IMAGE_DIRECTORY_ENTRY_EXPORT         = 0
	IMAGE_DIRECTORY_ENTRY_IMPORT         = 1
	IMAGE_DIRECTORY_ENTRY_RESOURCE       = 2
	IMAGE_DIRECTORY_ENTRY_EXCEPTION      = 3
	IMAGE_DIRECTORY_ENTRY_SECURITY       = 4
	IMAGE_DIRECTORY_ENTRY_BASERELOC      = 5
	IMAGE_DIRECTORY_ENTRY_DEBUG          = 6
	IMAGE_DIRECTORY_ENTRY_ARCHITECTURE   = 7
	IMAGE_DIRECTORY_ENTRY_GLOBALPTR      = 8
	IMAGE_DIRECTORY_ENTRY_TLS            = 9
	IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG    = 10
	IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT   = 11
	IMAGE_DIRECTORY_ENTRY_IAT            = 12
	IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT   = 13
	IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR = 14
)

IMAGE_DIRECTORY_ENTRY constants

View Source

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
const (
	IMAGE_FILE_RELOCS_STRIPPED         = 0x0001
	IMAGE_FILE_EXECUTABLE_IMAGE        = 0x0002
	IMAGE_FILE_LINE_NUMS_STRIPPED      = 0x0004
	IMAGE_FILE_LOCAL_SYMS_STRIPPED     = 0x0008
	IMAGE_FILE_AGGRESIVE_WS_TRIM       = 0x0010
	IMAGE_FILE_LARGE_ADDRESS_AWARE     = 0x0020
	IMAGE_FILE_BYTES_REVERSED_LO       = 0x0080
	IMAGE_FILE_32BIT_MACHINE           = 0x0100
	IMAGE_FILE_DEBUG_STRIPPED          = 0x0200
	IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP = 0x0400
	IMAGE_FILE_NET_RUN_FROM_SWAP       = 0x0800
	IMAGE_FILE_SYSTEM                  = 0x1000
	IMAGE_FILE_DLL                     = 0x2000
	IMAGE_FILE_UP_SYSTEM_ONLY          = 0x4000
	IMAGE_FILE_BYTES_REVERSED_HI       = 0x8000
)

Values of IMAGE_FILE_HEADER.Characteristics. These can be combined together.

View Source

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
const (
	IMAGE_SUBSYSTEM_UNKNOWN                  = 0
	IMAGE_SUBSYSTEM_NATIVE                   = 1
	IMAGE_SUBSYSTEM_WINDOWS_GUI              = 2
	IMAGE_SUBSYSTEM_WINDOWS_CUI              = 3
	IMAGE_SUBSYSTEM_OS2_CUI                  = 5
	IMAGE_SUBSYSTEM_POSIX_CUI                = 7
	IMAGE_SUBSYSTEM_NATIVE_WINDOWS           = 8
	IMAGE_SUBSYSTEM_WINDOWS_CE_GUI           = 9
	IMAGE_SUBSYSTEM_EFI_APPLICATION          = 10
	IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER  = 11
	IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER       = 12
	IMAGE_SUBSYSTEM_EFI_ROM                  = 13
	IMAGE_SUBSYSTEM_XBOX                     = 14
	IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION = 16
)

OptionalHeader64.Subsystem and OptionalHeader32.Subsystem values.

View Source

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
const (
	IMAGE_DLLCHARACTERISTICS_HIGH_ENTROPY_VA       = 0x0020
	IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE          = 0x0040
	IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY       = 0x0080
	IMAGE_DLLCHARACTERISTICS_NX_COMPAT             = 0x0100
	IMAGE_DLLCHARACTERISTICS_NO_ISOLATION          = 0x0200
	IMAGE_DLLCHARACTERISTICS_NO_SEH                = 0x0400
	IMAGE_DLLCHARACTERISTICS_NO_BIND               = 0x0800
	IMAGE_DLLCHARACTERISTICS_APPCONTAINER          = 0x1000
	IMAGE_DLLCHARACTERISTICS_WDM_DRIVER            = 0x2000
	IMAGE_DLLCHARACTERISTICS_GUARD_CF              = 0x4000
	IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE = 0x8000
)

OptionalHeader64.DllCharacteristics and OptionalHeader32.DllCharacteristics values. These can be combined together.

View Source

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
const (
	IMAGE_SCN_CNT_CODE               = 0x00000020
	IMAGE_SCN_CNT_INITIALIZED_DATA   = 0x00000040
	IMAGE_SCN_CNT_UNINITIALIZED_DATA = 0x00000080
	IMAGE_SCN_LNK_COMDAT             = 0x00001000
	IMAGE_SCN_MEM_DISCARDABLE        = 0x02000000
	IMAGE_SCN_MEM_EXECUTE            = 0x20000000
	IMAGE_SCN_MEM_READ               = 0x40000000
	IMAGE_SCN_MEM_WRITE              = 0x80000000
)

Section characteristics flags.

View Source

1
2
3
4
5
6
7
8
const (
	IMAGE_COMDAT_SELECT_NODUPLICATES = 1
	IMAGE_COMDAT_SELECT_ANY          = 2
	IMAGE_COMDAT_SELECT_SAME_SIZE    = 3
	IMAGE_COMDAT_SELECT_EXACT_MATCH  = 4
	IMAGE_COMDAT_SELECT_ASSOCIATIVE  = 5
	IMAGE_COMDAT_SELECT_LARGEST      = 6
)

These constants make up the possible values for the ‘Selection’ field in an AuxFormat5.

View Source

1
const COFFSymbolSize = 18

变量

This section is empty.

函数

This section is empty.

类型

type COFFSymbol <- go1.1

1
2
3
4
5
6
7
8
type COFFSymbol struct {
	Name               [8]uint8
	Value              uint32
	SectionNumber      int16
	Type               uint16
	StorageClass       uint8
	NumberOfAuxSymbols uint8
}

COFFSymbol represents single COFF symbol table record.

(*COFFSymbol) FullName <- go1.8

1
func (sym *COFFSymbol) FullName(st StringTable) (string, error)

FullName finds real name of symbol sym. Normally name is stored in sym.Name, but if it is longer then 8 characters, it is stored in COFF string table st instead.

type COFFSymbolAuxFormat5 <- go1.19

1
2
3
4
5
6
7
8
9
type COFFSymbolAuxFormat5 struct {
	Size           uint32
	NumRelocs      uint16
	NumLineNumbers uint16
	Checksum       uint32
	SecNum         uint16
	Selection      uint8
	// contains filtered or unexported fields
}

COFFSymbolAuxFormat5 describes the expected form of an aux symbol attached to a section definition symbol. The PE format defines a number of different aux symbol formats: format 1 for function definitions, format 2 for .be and .ef symbols, and so on. Format 5 holds extra info associated with a section definition, including number of relocations + line numbers, as well as COMDAT info. See https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#auxiliary-format-5-section-definitions for more on what’s going on here.

type DataDirectory <- go1.3

1
2
3
4
type DataDirectory struct {
	VirtualAddress uint32
	Size           uint32
}

type File

1
2
3
4
5
6
7
8
9
type File struct {
	FileHeader
	OptionalHeader any // of type *OptionalHeader32 or *OptionalHeader64
	Sections       []*Section
	Symbols        []*Symbol    // COFF symbols with auxiliary symbol records removed
	COFFSymbols    []COFFSymbol // all COFF symbols (including auxiliary symbol records)
	StringTable    StringTable
	// contains filtered or unexported fields
}

A File represents an open PE file.

func NewFile

1
func NewFile(r io.ReaderAt) (*File, error)

NewFile creates a new File for accessing a PE binary in an underlying reader.

func Open

1
func Open(name string) (*File, error)

Open opens the named file using os.Open and prepares it for use as a PE binary.

(*File) COFFSymbolReadSectionDefAux <- go1.19

1
func (f *File) COFFSymbolReadSectionDefAux(idx int) (*COFFSymbolAuxFormat5, error)

COFFSymbolReadSectionDefAux returns a blob of axiliary information (including COMDAT info) for a section definition symbol. Here ‘idx’ is the index of a section symbol in the main COFFSymbol array for the File. Return value is a pointer to the appropriate aux symbol struct. For more info, see:

auxiliary symbols: https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#auxiliary-symbol-records COMDAT sections: https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#comdat-sections-object-only auxiliary info for section definitions: https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#auxiliary-format-5-section-definitions

(*File) Close

1
func (f *File) Close() error

Close closes the File. If the File was created using NewFile directly instead of Open, Close has no effect.

(*File) DWARF

1
func (f *File) DWARF() (*dwarf.Data, error)

(*File) ImportedLibraries

1
func (f *File) ImportedLibraries() ([]string, error)

ImportedLibraries returns the names of all libraries referred to by the binary f that are expected to be linked with the binary at dynamic link time.

(*File) ImportedSymbols

1
func (f *File) ImportedSymbols() ([]string, error)

ImportedSymbols returns the names of all symbols referred to by the binary f that are expected to be satisfied by other libraries at dynamic load time. It does not return weak symbols.

(*File) Section

1
func (f *File) Section(name string) *Section

Section returns the first section with the given name, or nil if no such section exists.

type FileHeader

1
2
3
4
5
6
7
8
9
type FileHeader struct {
	Machine              uint16
	NumberOfSections     uint16
	TimeDateStamp        uint32
	PointerToSymbolTable uint32
	NumberOfSymbols      uint32
	SizeOfOptionalHeader uint16
	Characteristics      uint16
}

type FormatError

1
2
type FormatError struct {
}

FormatError is unused. The type is retained for compatibility.

(*FormatError) Error

1
func (e *FormatError) Error() string

type ImportDirectory

1
2
3
4
5
6
7
8
type ImportDirectory struct {
	OriginalFirstThunk uint32
	TimeDateStamp      uint32
	ForwarderChain     uint32
	Name               uint32
	FirstThunk         uint32
	// contains filtered or unexported fields
}

type OptionalHeader32 <- go1.3

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
type OptionalHeader32 struct {
	Magic                       uint16
	MajorLinkerVersion          uint8
	MinorLinkerVersion          uint8
	SizeOfCode                  uint32
	SizeOfInitializedData       uint32
	SizeOfUninitializedData     uint32
	AddressOfEntryPoint         uint32
	BaseOfCode                  uint32
	BaseOfData                  uint32
	ImageBase                   uint32
	SectionAlignment            uint32
	FileAlignment               uint32
	MajorOperatingSystemVersion uint16
	MinorOperatingSystemVersion uint16
	MajorImageVersion           uint16
	MinorImageVersion           uint16
	MajorSubsystemVersion       uint16
	MinorSubsystemVersion       uint16
	Win32VersionValue           uint32
	SizeOfImage                 uint32
	SizeOfHeaders               uint32
	CheckSum                    uint32
	Subsystem                   uint16
	DllCharacteristics          uint16
	SizeOfStackReserve          uint32
	SizeOfStackCommit           uint32
	SizeOfHeapReserve           uint32
	SizeOfHeapCommit            uint32
	LoaderFlags                 uint32
	NumberOfRvaAndSizes         uint32
	DataDirectory               [16]DataDirectory
}

type OptionalHeader64 <- go1.3

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
type OptionalHeader64 struct {
	Magic                       uint16
	MajorLinkerVersion          uint8
	MinorLinkerVersion          uint8
	SizeOfCode                  uint32
	SizeOfInitializedData       uint32
	SizeOfUninitializedData     uint32
	AddressOfEntryPoint         uint32
	BaseOfCode                  uint32
	ImageBase                   uint64
	SectionAlignment            uint32
	FileAlignment               uint32
	MajorOperatingSystemVersion uint16
	MinorOperatingSystemVersion uint16
	MajorImageVersion           uint16
	MinorImageVersion           uint16
	MajorSubsystemVersion       uint16
	MinorSubsystemVersion       uint16
	Win32VersionValue           uint32
	SizeOfImage                 uint32
	SizeOfHeaders               uint32
	CheckSum                    uint32
	Subsystem                   uint16
	DllCharacteristics          uint16
	SizeOfStackReserve          uint64
	SizeOfStackCommit           uint64
	SizeOfHeapReserve           uint64
	SizeOfHeapCommit            uint64
	LoaderFlags                 uint32
	NumberOfRvaAndSizes         uint32
	DataDirectory               [16]DataDirectory
}

type Reloc <- go1.8

1
2
3
4
5
type Reloc struct {
	VirtualAddress   uint32
	SymbolTableIndex uint32
	Type             uint16
}

Reloc represents a PE COFF relocation. Each section contains its own relocation list.

type Section

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
type Section struct {
	SectionHeader
	Relocs []Reloc

	// Embed ReaderAt for ReadAt method.
	// Do not embed SectionReader directly
	// to avoid having Read and Seek.
	// If a client wants Read and Seek it must use
	// Open() to avoid fighting over the seek offset
	// with other clients.
	io.ReaderAt
	// contains filtered or unexported fields
}

Section provides access to PE COFF section.

(*Section) Data

1
func (s *Section) Data() ([]byte, error)

Data reads and returns the contents of the PE section s.

(*Section) Open

1
func (s *Section) Open() io.ReadSeeker

Open returns a new ReadSeeker reading the PE section s.

type SectionHeader

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
type SectionHeader struct {
	Name                 string
	VirtualSize          uint32
	VirtualAddress       uint32
	Size                 uint32
	Offset               uint32
	PointerToRelocations uint32
	PointerToLineNumbers uint32
	NumberOfRelocations  uint16
	NumberOfLineNumbers  uint16
	Characteristics      uint32
}

SectionHeader is similar to SectionHeader32 with Name field replaced by Go string.

type SectionHeader32

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
type SectionHeader32 struct {
	Name                 [8]uint8
	VirtualSize          uint32
	VirtualAddress       uint32
	SizeOfRawData        uint32
	PointerToRawData     uint32
	PointerToRelocations uint32
	PointerToLineNumbers uint32
	NumberOfRelocations  uint16
	NumberOfLineNumbers  uint16
	Characteristics      uint32
}

SectionHeader32 represents real PE COFF section header.

type StringTable <- go1.8

1
type StringTable []byte

StringTable is a COFF string table.

(StringTable) String <- go1.8

1
func (st StringTable) String(start uint32) (string, error)

String extracts string from COFF string table st at offset start.

type Symbol <- go1.1

1
2
3
4
5
6
7
type Symbol struct {
	Name          string
	Value         uint32
	SectionNumber int16
	Type          uint16
	StorageClass  uint8
}

Symbol is similar to COFFSymbol with Name field replaced by Go string. Symbol also does not have NumberOfAuxSymbols.

6.7 - plan9obj

plan9obj

https://pkg.go.dev/debug/plan9obj@go1.20.1

Package plan9obj implements access to Plan 9 a.out object files.

Security

This package is not designed to be hardened against adversarial inputs, and is outside the scope of https://go.dev/security/policy. In particular, only basic validation is done when parsing object files. As such, care should be taken when parsing untrusted inputs, as parsing malformed files may consume significant resources, or cause panics.

常量

View Source

1
2
3
4
5
6
7
const (
	Magic64 = 0x8000 // 64-bit expanded header

	Magic386   = (4*11+0)*11 + 7
	MagicAMD64 = (4*26+0)*26 + 7 + Magic64
	MagicARM   = (4*20+0)*20 + 7
)

变量

View Source

1
var ErrNoSymbols = errors.New("no symbol section")

ErrNoSymbols is returned by File.Symbols if there is no such section in the File.

函数

This section is empty.

类型

type File

1
2
3
4
5
type File struct {
	FileHeader
	Sections []*Section
	// contains filtered or unexported fields
}

A File represents an open Plan 9 a.out file.

func NewFile

1
func NewFile(r io.ReaderAt) (*File, error)

NewFile creates a new File for accessing a Plan 9 binary in an underlying reader. The Plan 9 binary is expected to start at position 0 in the ReaderAt.

func Open

1
func Open(name string) (*File, error)

Open opens the named file using os.Open and prepares it for use as a Plan 9 a.out binary.

(*File) Close

1
func (f *File) Close() error

Close closes the File. If the File was created using NewFile directly instead of Open, Close has no effect.

(*File) Section

1
func (f *File) Section(name string) *Section

Section returns a section with the given name, or nil if no such section exists.

(*File) Symbols

1
func (f *File) Symbols() ([]Sym, error)

Symbols returns the symbol table for f.

type FileHeader

1
2
3
4
5
6
7
8
type FileHeader struct {
	Magic       uint32
	Bss         uint32
	Entry       uint64
	PtrSize     int
	LoadAddress uint64
	HdrSize     uint64
}

A FileHeader represents a Plan 9 a.out file header.

type Section

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
type Section struct {
	SectionHeader

	// Embed ReaderAt for ReadAt method.
	// Do not embed SectionReader directly
	// to avoid having Read and Seek.
	// If a client wants Read and Seek it must use
	// Open() to avoid fighting over the seek offset
	// with other clients.
	io.ReaderAt
	// contains filtered or unexported fields
}

A Section represents a single section in a Plan 9 a.out file.

(*Section) Data

1
func (s *Section) Data() ([]byte, error)

Data reads and returns the contents of the Plan 9 a.out section.

(*Section) Open

1
func (s *Section) Open() io.ReadSeeker

Open returns a new ReadSeeker reading the Plan 9 a.out section.

type SectionHeader

1
2
3
4
5
type SectionHeader struct {
	Name   string
	Size   uint32
	Offset uint32
}

A SectionHeader represents a single Plan 9 a.out section header. This structure doesn’t exist on-disk, but eases navigation through the object file.

type Sym

1
2
3
4
5
type Sym struct {
	Value uint64
	Type  rune
	Name  string
}

A Symbol represents an entry in a Plan 9 a.out symbol table section.

7 - encoding

7.1 - ascii85

ascii85

https://pkg.go.dev/encoding/ascii85@go1.20.1

Package ascii85 implements the ascii85 data encoding as used in the btoa tool and Adobe’s PostScript and PDF document formats.

常量

This section is empty.

变量

This section is empty.

函数

func Decode

1
func Decode(dst, src []byte, flush bool) (ndst, nsrc int, err error)

Decode decodes src into dst, returning both the number of bytes written to dst and the number consumed from src. If src contains invalid ascii85 data, Decode will return the number of bytes successfully written and a CorruptInputError. Decode ignores space and control characters in src. Often, ascii85-encoded data is wrapped in <~ and ~> symbols. Decode expects these to have been stripped by the caller.

If flush is true, Decode assumes that src represents the end of the input stream and processes it completely rather than wait for the completion of another 32-bit block.

NewDecoder wraps an io.Reader interface around Decode.

func Encode

1
func Encode(dst, src []byte) int

Encode encodes src into at most MaxEncodedLen(len(src)) bytes of dst, returning the actual number of bytes written.

The encoding handles 4-byte chunks, using a special encoding for the last fragment, so Encode is not appropriate for use on individual blocks of a large data stream. Use NewEncoder() instead.

Often, ascii85-encoded data is wrapped in <~ and ~> symbols. Encode does not add these.

func MaxEncodedLen

1
func MaxEncodedLen(n int) int

MaxEncodedLen returns the maximum length of an encoding of n source bytes.

func NewDecoder

1
func NewDecoder(r io.Reader) io.Reader

NewDecoder constructs a new ascii85 stream decoder.

func NewEncoder

1
func NewEncoder(w io.Writer) io.WriteCloser

NewEncoder returns a new ascii85 stream encoder. Data written to the returned writer will be encoded and then written to w. Ascii85 encodings operate in 32-bit blocks; when finished writing, the caller must Close the returned encoder to flush any trailing partial block.

类型

type CorruptInputError

1
type CorruptInputError int64

(CorruptInputError) Error

1
func (e CorruptInputError) Error() string

7.2 - asn1

asn1

https://pkg.go.dev/encoding/asn1@go1.20.1

Package asn1 implements parsing of DER-encoded ASN.1 data structures, as defined in ITU-T Rec X.690.

See also “A Layman’s Guide to a Subset of ASN.1, BER, and DER,” http://luca.ntop.org/Teaching/Appunti/asn1.html.

常量

View Source

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
const (
	TagBoolean         = 1
	TagInteger         = 2
	TagBitString       = 3
	TagOctetString     = 4
	TagNull            = 5
	TagOID             = 6
	TagEnum            = 10
	TagUTF8String      = 12
	TagSequence        = 16
	TagSet             = 17
	TagNumericString   = 18
	TagPrintableString = 19
	TagT61String       = 20
	TagIA5String       = 22
	TagUTCTime         = 23
	TagGeneralizedTime = 24
	TagGeneralString   = 27
	TagBMPString       = 30
)

ASN.1 tags represent the type of the following object.

View Source

1
2
3
4
5
6
const (
	ClassUniversal       = 0
	ClassApplication     = 1
	ClassContextSpecific = 2
	ClassPrivate         = 3
)

ASN.1 class types represent the namespace of the tag.

变量

View Source

1
var NullBytes = []byte{TagNull, 0}

NullBytes contains bytes representing the DER-encoded ASN.1 NULL type.

View Source

1
var NullRawValue = RawValue{Tag: TagNull}

NullRawValue is a RawValue with its Tag set to the ASN.1 NULL type tag (5).

函数

func Marshal

1
func Marshal(val any) ([]byte, error)

Marshal returns the ASN.1 encoding of val.

In addition to the struct tags recognised by Unmarshal, the following can be used:

ia5:         causes strings to be marshaled as ASN.1, IA5String values
omitempty:   causes empty slices to be skipped
printable:   causes strings to be marshaled as ASN.1, PrintableString values
utf8:        causes strings to be marshaled as ASN.1, UTF8String values
utc:         causes time.Time to be marshaled as ASN.1, UTCTime values
generalized: causes time.Time to be marshaled as ASN.1, GeneralizedTime values

func MarshalWithParams <- go1.10

1
func MarshalWithParams(val any, params string) ([]byte, error)

MarshalWithParams allows field parameters to be specified for the top-level element. The form of the params is the same as the field tags.

func Unmarshal

1
func Unmarshal(b []byte, val any) (rest []byte, err error)

Unmarshal parses the DER-encoded ASN.1 data structure b and uses the reflect package to fill in an arbitrary value pointed at by val. Because Unmarshal uses the reflect package, the structs being written to must use upper case field names. If val is nil or not a pointer, Unmarshal returns an error.

After parsing b, any bytes that were leftover and not used to fill val will be returned in rest. When parsing a SEQUENCE into a struct, any trailing elements of the SEQUENCE that do not have matching fields in val will not be included in rest, as these are considered valid elements of the SEQUENCE and not trailing data.

An ASN.1 INTEGER can be written to an int, int32, int64, or *big.Int (from the math/big package). If the encoded value does not fit in the Go type, Unmarshal returns a parse error.

An ASN.1 BIT STRING can be written to a BitString.

An ASN.1 OCTET STRING can be written to a []byte.

An ASN.1 OBJECT IDENTIFIER can be written to an ObjectIdentifier.

An ASN.1 ENUMERATED can be written to an Enumerated.

An ASN.1 UTCTIME or GENERALIZEDTIME can be written to a time.Time.

An ASN.1 PrintableString, IA5String, or NumericString can be written to a string.

Any of the above ASN.1 values can be written to an interface{}. The value stored in the interface has the corresponding Go type. For integers, that type is int64.

An ASN.1 SEQUENCE OF x or SET OF x can be written to a slice if an x can be written to the slice’s element type.

An ASN.1 SEQUENCE or SET can be written to a struct if each of the elements in the sequence can be written to the corresponding element in the struct.

The following tags on struct fields have special meaning to Unmarshal:

application specifies that an APPLICATION tag is used
private     specifies that a PRIVATE tag is used
default:x   sets the default value for optional integer fields (only used if optional is also present)
explicit    specifies that an additional, explicit tag wraps the implicit one
optional    marks the field as ASN.1 OPTIONAL
set         causes a SET, rather than a SEQUENCE type to be expected
tag:x       specifies the ASN.1 tag number; implies ASN.1 CONTEXT SPECIFIC

When decoding an ASN.1 value with an IMPLICIT tag into a string field, Unmarshal will default to a PrintableString, which doesn’t support characters such as ‘@’ and ‘&’. To force other encodings, use the following tags:

ia5     causes strings to be unmarshaled as ASN.1 IA5String values
numeric causes strings to be unmarshaled as ASN.1 NumericString values
utf8    causes strings to be unmarshaled as ASN.1 UTF8String values

If the type of the first field of a structure is RawContent then the raw ASN1 contents of the struct will be stored in it.

If the name of a slice type ends with “SET” then it’s treated as if the “set” tag was set on it. This results in interpreting the type as a SET OF x rather than a SEQUENCE OF x. This can be used with nested slices where a struct tag cannot be given.

Other ASN.1 types are not supported; if it encounters them, Unmarshal returns a parse error.

func UnmarshalWithParams

1
func UnmarshalWithParams(b []byte, val any, params string) (rest []byte, err error)

UnmarshalWithParams allows field parameters to be specified for the top-level element. The form of the params is the same as the field tags.

类型

type BitString

1
2
3
4
type BitString struct {
	Bytes     []byte // bits packed into bytes.
	BitLength int    // length in bits.
}

BitString is the structure to use when you want an ASN.1 BIT STRING type. A bit string is padded up to the nearest byte in memory and the number of valid bits is recorded. Padding bits will be zero.

(BitString) At

1
func (b BitString) At(i int) int

At returns the bit at the given index. If the index is out of range it returns 0.

(BitString) RightAlign

1
func (b BitString) RightAlign() []byte

RightAlign returns a slice where the padding bits are at the beginning. The slice may share memory with the BitString.

type Enumerated

1
type Enumerated int

An Enumerated is represented as a plain int.

type Flag

1
type Flag bool

A Flag accepts any data and is set to true if present.

type ObjectIdentifier

1
type ObjectIdentifier []int

An ObjectIdentifier represents an ASN.1 OBJECT IDENTIFIER.

(ObjectIdentifier) Equal

1
func (oi ObjectIdentifier) Equal(other ObjectIdentifier) bool

Equal reports whether oi and other represent the same identifier.

(ObjectIdentifier) String <- go1.3

1
func (oi ObjectIdentifier) String() string

type RawContent

1
type RawContent []byte

RawContent is used to signal that the undecoded, DER data needs to be preserved for a struct. To use it, the first field of the struct must have this type. It’s an error for any of the other fields to have this type.

type RawValue

1
2
3
4
5
6
type RawValue struct {
	Class, Tag int
	IsCompound bool
	Bytes      []byte
	FullBytes  []byte // includes the tag and length
}

A RawValue represents an undecoded ASN.1 object.

type StructuralError

1
2
3
type StructuralError struct {
	Msg string
}

A StructuralError suggests that the ASN.1 data is valid, but the Go type which is receiving it doesn’t match.

(StructuralError) Error

1
func (e StructuralError) Error() string

type SyntaxError

1
2
3
type SyntaxError struct {
	Msg string
}

A SyntaxError suggests that the ASN.1 data is invalid.

(SyntaxError) Error

1
func (e SyntaxError) Error() string

7.3 - base32

base32

https://pkg.go.dev/encoding/base32@go1.20.1

Package base32 implements base32 encoding as specified by RFC 4648.

常量

View Source

1
2
3
4
5
const (
	StdPadding rune = '=' // Standard padding character
	NoPadding  rune = -1  // No padding

)

变量

View Source

1
var HexEncoding = NewEncoding(encodeHex)

HexEncoding is the “Extended Hex Alphabet” defined in RFC 4648. It is typically used in DNS.

View Source

1
var StdEncoding = NewEncoding(encodeStd)

StdEncoding is the standard base32 encoding, as defined in RFC 4648.

函数

func NewDecoder

1
func NewDecoder(enc *Encoding, r io.Reader) io.Reader

NewDecoder constructs a new base32 stream decoder.

func NewEncoder

1
func NewEncoder(enc *Encoding, w io.Writer) io.WriteCloser

NewEncoder returns a new base32 stream encoder. Data written to the returned writer will be encoded using enc and then written to w. Base32 encodings operate in 5-byte blocks; when finished writing, the caller must Close the returned encoder to flush any partially written blocks.

Example

类型

type CorruptInputError

1
type CorruptInputError int64

(CorruptInputError) Error

1
func (e CorruptInputError) Error() string

type Encoding

1
2
3
type Encoding struct {
	// contains filtered or unexported fields
}

An Encoding is a radix 32 encoding/decoding scheme, defined by a 32-character alphabet. The most common is the “base32” encoding introduced for SASL GSSAPI and standardized in RFC 4648. The alternate “base32hex” encoding is used in DNSSEC.

func NewEncoding

1
func NewEncoding(encoder string) *Encoding

NewEncoding returns a new Encoding defined by the given alphabet, which must be a 32-byte string.

(*Encoding) Decode

1
func (enc *Encoding) Decode(dst, src []byte) (n int, err error)

Decode decodes src using the encoding enc. It writes at most DecodedLen(len(src)) bytes to dst and returns the number of bytes written. If src contains invalid base32 data, it will return the number of bytes successfully written and CorruptInputError. New line characters (\r and \n) are ignored.

Example

(*Encoding) DecodeString

1
func (enc *Encoding) DecodeString(s string) ([]byte, error)

DecodeString returns the bytes represented by the base32 string s.

Example

(*Encoding) DecodedLen

1
func (enc *Encoding) DecodedLen(n int) int

DecodedLen returns the maximum length in bytes of the decoded data corresponding to n bytes of base32-encoded data.

(*Encoding) Encode

1
func (enc *Encoding) Encode(dst, src []byte)

Encode encodes src using the encoding enc, writing EncodedLen(len(src)) bytes to dst.

The encoding pads the output to a multiple of 8 bytes, so Encode is not appropriate for use on individual blocks of a large data stream. Use NewEncoder() instead.

Example

(*Encoding) EncodeToString

1
func (enc *Encoding) EncodeToString(src []byte) string

EncodeToString returns the base32 encoding of src.

Example

(*Encoding) EncodedLen

1
func (enc *Encoding) EncodedLen(n int) int

EncodedLen returns the length in bytes of the base32 encoding of an input buffer of length n.

(Encoding) WithPadding <- go1.9

1
func (enc Encoding) WithPadding(padding rune) *Encoding

WithPadding creates a new encoding identical to enc except with a specified padding character, or NoPadding to disable padding. The padding character must not be ‘\r’ or ‘\n’, must not be contained in the encoding’s alphabet and must be a rune equal or below ‘\xff’.

7.4 - base64

base64

https://pkg.go.dev/encoding/base64@go1.20.1

Package base64 implements base64 encoding as specified by RFC 4648.

包 base64 实现了 RFC 4648 所规定的 base64 编码。

Example

常量

View Source

1
2
3
4
5
const (
	StdPadding rune = '=' // Standard padding character // 标准填充字符
	NoPadding  rune = -1  // No padding  // 无填充字符

)

变量

View Source

1
var RawStdEncoding = StdEncoding.WithPadding(NoPadding)

RawStdEncoding is the standard raw, unpadded base64 encoding, as defined in RFC 4648 section 3.2. This is the same as StdEncoding but omits padding characters.

RawStdEncoding是标准的原始、无填充的base64编码,定义于RFC 4648第3.2节。这与StdEncoding相同,但省略了填充字符。

View Source

1
var RawURLEncoding = URLEncoding.WithPadding(NoPadding)

RawURLEncoding is the unpadded alternate base64 encoding defined in RFC 4648. It is typically used in URLs and file names. This is the same as URLEncoding but omits padding characters.

RawURLEncoding是RFC 4648中定义的无填充的另一种base64编码。它通常在URL和文件名中使用。这与URLEncoding相同,但省略了填充字符。

View Source

1
var StdEncoding = NewEncoding(encodeStd)

StdEncoding is the standard base64 encoding, as defined in RFC 4648.

StdEncoding是标准的base64编码,如RFC 4648所定义。

View Source

1
var URLEncoding = NewEncoding(encodeURL)

URLEncoding is the alternate base64 encoding defined in RFC 4648. It is typically used in URLs and file names.

URLEncoding是RFC 4648中定义的备用base64编码。它通常在URL和文件名中使用。

函数

func NewDecoder

1
func NewDecoder(enc *Encoding, r io.Reader) io.Reader

NewDecoder constructs a new base64 stream decoder.

NewDecoder构建一个新的base64流解码器。

func NewEncoder

1
func NewEncoder(enc *Encoding, w io.Writer) io.WriteCloser

NewEncoder returns a new base64 stream encoder. Data written to the returned writer will be encoded using enc and then written to w. Base64 encodings operate in 4-byte blocks; when finished writing, the caller must Close the returned encoder to flush any partially written blocks.

NewEncoder返回一个新的base64流编码器。写入返回的写入器的数据将使用enc进行编码,然后写入w。Base64编码以4字节的块进行操作;当写完后,调用者必须关闭返回的编码器以冲刷任何部分写入的块。

Example

类型

type CorruptInputError

1
type CorruptInputError int64

(CorruptInputError) Error

1
func (e CorruptInputError) Error() string

type Encoding

1
2
3
type Encoding struct {
	// contains filtered or unexported fields
}

An Encoding is a radix 64 encoding/decoding scheme, defined by a 64-character alphabet. The most common encoding is the “base64” encoding defined in RFC 4648 and used in MIME (RFC 2045) and PEM (RFC 1421). RFC 4648 also defines an alternate encoding, which is the standard encoding with - and _ substituted for + and /.

编码是一个弧度为64的编码/解码方案,由一个64字符的字母表定义。最常见的编码是RFC 4648中定义的 “base64 “编码,在MIME(RFC 2045)和PEM(RFC 1421)中使用。RFC 4648还定义了一个备用编码,即用-和_代替+和/的标准编码。

func NewEncoding

1
func NewEncoding(encoder string) *Encoding

NewEncoding returns a new padded Encoding defined by the given alphabet, which must be a 64-byte string that does not contain the padding character or CR / LF (’\r’, ‘\n’). The resulting Encoding uses the default padding character (’=’), which may be changed or disabled via WithPadding.

NewEncoding返回一个由给定字母定义的新的填充编码,它必须是一个64字节的字符串,不包含填充字符或CR / LF(’\r’, ‘\n’)。产生的Encoding使用默认的padding字符(’=’),可以通过WithPadding改变或禁用。

(*Encoding) Decode

1
func (enc *Encoding) Decode(dst, src []byte) (n int, err error)

Decode decodes src using the encoding enc. It writes at most DecodedLen(len(src)) bytes to dst and returns the number of bytes written. If src contains invalid base64 data, it will return the number of bytes successfully written and CorruptInputError. New line characters (\r and \n) are ignored.

Decode使用enc编码对src进行解码。它最多向dst写入DecodedLen(len(src))字节,并返回写入的字节数。如果src包含无效的base64数据,它将返回成功写入的字节数和CorruptInputError。新行字符(\r 和 \n)被忽略。

Example

(*Encoding) DecodeString

1
func (enc *Encoding) DecodeString(s string) ([]byte, error)

DecodeString returns the bytes represented by the base64 string s.

DecodeString返回base64字符串s所代表的字节。

Example

(*Encoding) DecodedLen

1
func (enc *Encoding) DecodedLen(n int) int

DecodedLen returns the maximum length in bytes of the decoded data corresponding to n bytes of base64-encoded data.

DecodedLen返回对应于base64编码的n个字节的解码数据的最大长度(字节)。

(*Encoding) Encode

1
func (enc *Encoding) Encode(dst, src []byte)

Encode encodes src using the encoding enc, writing EncodedLen(len(src)) bytes to dst.

Encode使用enc编码对src进行编码,向dst写入EncodedLen(len(src))字节。

The encoding pads the output to a multiple of 4 bytes, so Encode is not appropriate for use on individual blocks of a large data stream. Use NewEncoder() instead.

编码将输出填充为4字节的倍数,所以Encode不适合用于大数据流的单个块。请使用NewEncoder()代替。

Example

(*Encoding) EncodeToString

1
func (enc *Encoding) EncodeToString(src []byte) string

EncodeToString returns the base64 encoding of src.

EncodeToString返回src的base64编码。

Example

(*Encoding) EncodedLen

1
func (enc *Encoding) EncodedLen(n int) int

EncodedLen returns the length in bytes of the base64 encoding of an input buffer of length n.

EncodedLen返回一个长度为n的输入缓冲区的base64编码的字节长度。

(Encoding) Strict <- go1.8

1
func (enc Encoding) Strict() *Encoding

Strict creates a new encoding identical to enc except with strict decoding enabled. In this mode, the decoder requires that trailing padding bits are zero, as described in RFC 4648 section 3.5.

严格创建一个与enc相同的新编码,只是启用了严格解码。在这种模式下,解码器要求尾部填充位为零,如RFC 4648第3.5节所述。

Note that the input is still malleable, as new line characters (CR and LF) are still ignored.

注意,输入仍然是可塑的,因为新的行字符(CR和LF)仍然被忽略。

(Encoding) WithPadding <- go1.5

1
func (enc Encoding) WithPadding(padding rune) *Encoding

WithPadding creates a new encoding identical to enc except with a specified padding character, or NoPadding to disable padding. The padding character must not be ‘\r’ or ‘\n’, must not be contained in the encoding’s alphabet and must be a rune equal or below ‘\xff’.

WithPadding创建一个与enc相同的新编码,除了指定的padding字符,或者用NoPadding来禁用padding。填充字符不能是’\r’或’\n’,不能包含在编码的字母表中,必须是等于或低于’\xff’的符文。

7.5 - binary

binary

https://pkg.go.dev/encoding/binary@go1.20.1

Package binary implements simple translation between numbers and byte sequences and encoding and decoding of varints.

Numbers are translated by reading and writing fixed-size values. A fixed-size value is either a fixed-size arithmetic type (bool, int8, uint8, int16, float32, complex64, …) or an array or struct containing only fixed-size values.

The varint functions encode and decode single integer values using a variable-length encoding; smaller values require fewer bytes. For a specification, see https://developers.google.com/protocol-buffers/docs/encoding.

This package favors simplicity over efficiency. Clients that require high-performance serialization, especially for large data structures, should look at more advanced solutions such as the encoding/gob package or protocol buffers.

常量

View Source

1
2
3
4
5
const (
	MaxVarintLen16 = 3
	MaxVarintLen32 = 5
	MaxVarintLen64 = 10
)

MaxVarintLenN is the maximum length of a varint-encoded N-bit integer.

变量

View Source

1
var BigEndian bigEndian

BigEndian is the big-endian implementation of ByteOrder and AppendByteOrder.

View Source

1
var LittleEndian littleEndian

LittleEndian is the little-endian implementation of ByteOrder and AppendByteOrder.

函数

func AppendUvarint <- go1.19

1
func AppendUvarint(buf []byte, x uint64) []byte

AppendUvarint appends the varint-encoded form of x, as generated by PutUvarint, to buf and returns the extended buffer.

func AppendVarint <- go1.19

1
func AppendVarint(buf []byte, x int64) []byte

AppendVarint appends the varint-encoded form of x, as generated by PutVarint, to buf and returns the extended buffer.

func PutUvarint

1
func PutUvarint(buf []byte, x uint64) int

PutUvarint encodes a uint64 into buf and returns the number of bytes written. If the buffer is too small, PutUvarint will panic.

Example

func PutVarint

1
func PutVarint(buf []byte, x int64) int

PutVarint encodes an int64 into buf and returns the number of bytes written. If the buffer is too small, PutVarint will panic.

Example

func Read

1
func Read(r io.Reader, order ByteOrder, data any) error

Read reads structured binary data from r into data. Data must be a pointer to a fixed-size value or a slice of fixed-size values. Bytes read from r are decoded using the specified byte order and written to successive fields of the data. When decoding boolean values, a zero byte is decoded as false, and any other non-zero byte is decoded as true. When reading into structs, the field data for fields with blank (_) field names is skipped; i.e., blank field names may be used for padding. When reading into a struct, all non-blank fields must be exported or Read may panic.

The error is EOF only if no bytes were read. If an EOF happens after reading some but not all the bytes, Read returns ErrUnexpectedEOF.

Example
Example

func ReadUvarint

1
func ReadUvarint(r io.ByteReader) (uint64, error)

ReadUvarint reads an encoded unsigned integer from r and returns it as a uint64. The error is EOF only if no bytes were read. If an EOF happens after reading some but not all the bytes, ReadUvarint returns io.ErrUnexpectedEOF.

func ReadVarint

1
func ReadVarint(r io.ByteReader) (int64, error)

ReadVarint reads an encoded signed integer from r and returns it as an int64. The error is EOF only if no bytes were read. If an EOF happens after reading some but not all the bytes, ReadVarint returns io.ErrUnexpectedEOF.

func Size

1
func Size(v any) int

Size returns how many bytes Write would generate to encode the value v, which must be a fixed-size value or a slice of fixed-size values, or a pointer to such data. If v is neither of these, Size returns -1.

func Uvarint

1
func Uvarint(buf []byte) (uint64, int)

Uvarint decodes a uint64 from buf and returns that value and the number of bytes read (> 0). If an error occurred, the value is 0 and the number of bytes n is <= 0 meaning:

n == 0: buf too small
n  < 0: value larger than 64 bits (overflow)
        and -n is the number of bytes read
Example

func Varint

1
func Varint(buf []byte) (int64, int)

Varint decodes an int64 from buf and returns that value and the number of bytes read (> 0). If an error occurred, the value is 0 and the number of bytes n is <= 0 with the following meaning:

n == 0: buf too small
n  < 0: value larger than 64 bits (overflow)
        and -n is the number of bytes read
Example

func Write

1
func Write(w io.Writer, order ByteOrder, data any) error

Write writes the binary representation of data into w. Data must be a fixed-size value or a slice of fixed-size values, or a pointer to such data. Boolean values encode as one byte: 1 for true, and 0 for false. Bytes written to w are encoded using the specified byte order and read from successive fields of the data. When writing structs, zero values are written for fields with blank (_) field names.

Example
Example

类型

type AppendByteOrder <- go1.19

1
2
3
4
5
6
type AppendByteOrder interface {
	AppendUint16([]byte, uint16) []byte
	AppendUint32([]byte, uint32) []byte
	AppendUint64([]byte, uint64) []byte
	String() string
}

AppendByteOrder specifies how to append 16-, 32-, or 64-bit unsigned integers into a byte slice.

type ByteOrder

1
2
3
4
5
6
7
8
9
type ByteOrder interface {
	Uint16([]byte) uint16
	Uint32([]byte) uint32
	Uint64([]byte) uint64
	PutUint16([]byte, uint16)
	PutUint32([]byte, uint32)
	PutUint64([]byte, uint64)
	String() string
}

A ByteOrder specifies how to convert byte slices into 16-, 32-, or 64-bit unsigned integers.

Example

7.6 - csv

csv

https://pkg.go.dev/encoding/csv@go1.20.1

Package csv reads and writes comma-separated values (CSV) files. There are many kinds of CSV files; this package supports the format described in RFC 4180.

csv包读取和写入逗号分隔的值(CSV)文件。有许多种CSV文件;这个包支持RFC 4180中描述的格式。

A csv file contains zero or more records of one or more fields per record. Each record is separated by the newline character. The final record may optionally be followed by a newline character.

一个csv文件包含零个或多个记录,每个记录有一个或多个字段。每条记录由换行符分隔。最后一条记录后面可以选择换行符。

field1,field2,field3

White space is considered part of a field.

白色空间被认为是字段的一部分。

Carriage returns before newline characters are silently removed.

换行符之前的回车符会被默默地删除。

Blank lines are ignored. A line with only whitespace characters (excluding the ending newline character) is not considered a blank line.

空白行被忽略。只有空白字符的行(不包括结尾的换行字符)不被视为空行。

Fields which start and stop with the quote character " are called quoted-fields. The beginning and ending quote are not part of the field.

以引号字符"“开始和结束的字段被称为引号字段。开始和结束的引号不是字段的一部分。

The source:

来源:

normal string,"quoted-field"

results in the fields

的结果是字段

{`normal string`, `quoted-field`}

Within a quoted-field a quote character followed by a second quote character is considered a single quote.

在一个带引号的字段内,一个引号字符后面的第二个引号字符被认为是一个单引号。

"the ""word"" is true","a ""quoted-field"""

results in

结果是

{`the "word" is true`, `a "quoted-field"`}

Newlines and commas may be included in a quoted-field

换行符和逗号可以包含在一个引号字段中。

"Multi-line
field","comma is ,"

results in

结果是

{`Multi-line
field`, `comma is ,`}

常量

This section is empty.

变量

View Source

1
2
3
4
5
6
7
8
9
var (
	ErrBareQuote  = errors.New("bare \" in non-quoted-field")
	ErrQuote      = errors.New("extraneous or missing \" in quoted-field")
	ErrFieldCount = errors.New("wrong number of fields")

	// Deprecated: ErrTrailingComma is no longer used.
	// 已废弃:ErrTrailingComma不再使用。
	ErrTrailingComma = errors.New("extra delimiter at end of line")
)

These are the errors that can be returned in ParseError.Err.

这些是可以在ParseError.Err中返回的错误。

函数

This section is empty.

类型

type ParseError

1
2
3
4
5
6
type ParseError struct {
	StartLine int   // Line where the record starts// 记录开始的那一行
	Line      int   // Line where the error occurred// 发生错误的那一行
	Column    int   // Column (1-based byte index) where the error occurred // 发生错误的那一列(基于1的字节索引)。
	Err       error // The actual error // 实际的错误
}

A ParseError is returned for parsing errors. Line numbers are 1-indexed and columns are 0-indexed.

对于解析错误会返回一个ParseError。行号是1-索引的,列是0-索引的。

(*ParseError) Error

1
func (e *ParseError) Error() string

(*ParseError) Unwrap <- go1.13

1
func (e *ParseError) Unwrap() error

type Reader

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
type Reader struct {
	// Comma is the field delimiter.
	// It is set to comma (',') by NewReader.
	// Comma must be a valid rune and must not be \r, \n,
	// or the Unicode replacement character (0xFFFD).
	// 逗号是字段分隔符。
	// 它被NewReader设置为逗号(',')。
	// 逗号必须是一个有效的符文,不能是 \r, \n,
	// 或Unicode替换字符(0xFFFD)。
	Comma rune

	// Comment, if not 0, is the comment character. Lines beginning with the
	// Comment character without preceding whitespace are ignored.
	// With leading whitespace the Comment character becomes part of the
	// field, even if TrimLeadingSpace is true.
	// Comment must be a valid rune and must not be \r, \n,
	// or the Unicode replacement character (0xFFFD).
	// It must also not be equal to Comma.
	//注释,如果不是0,就是注释字符。以Comment字符开始的行,如果没有前面的空白,将被忽略。
	// 如果有前导空白,Comment字符将成为字段的一部分,即使TrimLeadingSpace为真。
	// Comment必须是一个有效的符文,不能是 \r, \n, 或Unicode替换字符(0xFFFD)。
	// 它也不能等于逗号。
	Comment rune

	// FieldsPerRecord is the number of expected fields per record.
	// If FieldsPerRecord is positive, Read requires each record to
	// have the given number of fields. If FieldsPerRecord is 0, Read sets it to
	// the number of fields in the first record, so that future records must
	// have the same field count. If FieldsPerRecord is negative, no check is
	// made and records may have a variable number of fields.
	// FieldsPerRecord是每条记录的预期字段数。
	// 如果FieldsPerRecord是正数,Read要求每条记录都有给定的字段数。如果FieldsPerRecord为0,Read将其设置为第一条记录的字段数,这样以后的记录必须有相同的字段数。如果FieldsPerRecord为负数,则不做检查,记录可能有可变的字段数。
	FieldsPerRecord int

	// If LazyQuotes is true, a quote may appear in an unquoted field and a
	// non-doubled quote may appear in a quoted field.
	// 如果LazyQuotes为真,一个引号可能出现在一个无引号的字段中,一个非双引号可能出现在一个有引号的字段中。
	LazyQuotes bool

	// If TrimLeadingSpace is true, leading white space in a field is ignored.
	// This is done even if the field delimiter, Comma, is white space.
	// 如果TrimLeadingSpace为真,字段中的前导空白将被忽略。
	// 即使字段的分隔符Comma是空白的,也会这样做。
	TrimLeadingSpace bool

	// ReuseRecord controls whether calls to Read may return a slice sharing
	// the backing array of the previous call's returned slice for performance.
	// By default, each call to Read returns newly allocated memory owned by the caller.
	// ReuseRecord控制对Read的调用是否可以返回共享前一次调用返回的片断的支持数组的片断,以提高性能。
	// 默认情况下,每次对Read的调用都会返回由调用者拥有的新分配的内存。
	ReuseRecord bool

	// Deprecated: TrailingComma is no longer used.
	// 已废弃:不再使用TrailingComma。
	TrailingComma bool
	// contains filtered or unexported fields
}

A Reader reads records from a CSV-encoded file.

Reader 从一个CSV编码的文件中读取记录。

As returned by NewReader, a Reader expects input conforming to RFC 4180. The exported fields can be changed to customize the details before the first call to Read or ReadAll.

正如NewReader所返回的那样,Reader期望输入的内容符合RFC 4180的规定。在第一次调用Read或ReadAll之前,导出的字段可以被改变以定制细节。

The Reader converts all \r\n sequences in its input to plain \n, including in multiline field values, so that the returned data does not depend on which line-ending convention an input file uses.

Reader 将其输入中的所有\r\n序列转换为普通的\n,包括在多行字段值中,因此返回的数据不依赖于输入文件使用的行结束惯例。

Example
Example

func NewReader

1
func NewReader(r io.Reader) *Reader

NewReader returns a new Reader that reads from r.

NewReader返回一个新的阅读器,从r中读取数据。

(*Reader) FieldPos <- go1.17

1
func (r *Reader) FieldPos(field int) (line, column int)

FieldPos returns the line and column corresponding to the start of the field with the given index in the slice most recently returned by Read. Numbering of lines and columns starts at 1; columns are counted in bytes, not runes.

FieldPos返回对应于最近由Read返回的片断中具有给定索引的字段开始的行和列。行和列的编号从1开始;列的计数单位是字节,而不是符码。

If this is called with an out-of-bounds index, it panics.

如果在调用这个函数时,索引超出了范围,它就会惊慌失措。

(*Reader) InputOffset <- go1.19

1
func (r *Reader) InputOffset() int64

InputOffset returns the input stream byte offset of the current reader position. The offset gives the location of the end of the most recently read row and the beginning of the next row.

InputOffset返回当前阅读器位置的输入流字节偏移。这个偏移量给出了最近读取的行的结束和下一行的开始的位置。

(*Reader) Read

1
func (r *Reader) Read() (record []string, err error)

Read reads one record (a slice of fields) from r. If the record has an unexpected number of fields, Read returns the record along with the error ErrFieldCount. Except for that case, Read always returns either a non-nil record or a non-nil error, but not both. If there is no data left to be read, Read returns nil, io.EOF. If ReuseRecord is true, the returned slice may be shared between multiple calls to Read.

如果记录有一个意外的字段数,Read会返回记录和错误ErrFieldCount。除了这种情况,Read总是返回一个非空的记录或一个非空的错误,但不会同时返回。如果没有数据可读,Read返回nil,即io.EOF。如果ReuseRecord为真,返回的片断可以在多次调用Read时共享。

(*Reader) ReadAll

1
func (r *Reader) ReadAll() (records [][]string, err error)

ReadAll reads all the remaining records from r. Each record is a slice of fields. A successful call returns err == nil, not err == io.EOF. Because ReadAll is defined to read until EOF, it does not treat end of file as an error to be reported.

ReadAll从r读取所有剩余的记录。一个成功的调用返回err == nil,而不是err == io.EOF。因为ReadAll被定义为读到EOF为止,它不把文件结束作为一个错误来报告。

Example

type Writer

1
2
3
4
5
type Writer struct {
	Comma   rune // Field delimiter (set to ',' by NewWriter) // 字段分隔符(NewWriter设置为',' )。
	UseCRLF bool // True to use \r\n as the line terminator // True,使用 \r\n 作为行结束符。
	// contains filtered or unexported fields
}

A Writer writes records using CSV encoding.

Writer使用CSV编码来写记录。

As returned by NewWriter, a Writer writes records terminated by a newline and uses ‘,’ as the field delimiter. The exported fields can be changed to customize the details before the first call to Write or WriteAll.

正如NewWriter所返回的那样,Writer写入的记录以换行方式结束,并使用’,‘作为字段分隔符。在第一次调用Write或WriteAll之前,可以改变导出的字段以定制细节。

Comma is the field delimiter.

逗号是字段分隔符。

If UseCRLF is true, the Writer ends each output line with \r\n instead of \n.

如果UseCRLF为真,Writer会以\r\n而不是\n结束每个输出行。

The writes of individual records are buffered. After all data has been written, the client should call the Flush method to guarantee all data has been forwarded to the underlying io.Writer. Any errors that occurred should be checked by calling the Error method.

单个记录的写入是缓冲的。在所有数据被写入后,客户端应该调用Flush方法以保证所有数据都被转发到底层的io.Writer。任何发生的错误都应该通过调用Error方法来检查。

Example

func NewWriter

1
func NewWriter(w io.Writer) *Writer

NewWriter returns a new Writer that writes to w.

NewWriter返回一个新的写入w的Writer。

(*Writer) Error <- go1.1

1
func (w *Writer) Error() error

Error reports any error that has occurred during a previous Write or Flush.

Error报告在之前的写或刷新过程中发生的任何错误。

(*Writer) Flush

1
func (w *Writer) Flush()

Flush writes any buffered data to the underlying io.Writer. To check if an error occurred during the Flush, call Error.

Flush将任何缓冲的数据写入底层的io.Writer。要检查在Flush过程中是否有错误发生,请调用Error。

(*Writer) Write

1
func (w *Writer) Write(record []string) error

Write writes a single CSV record to w along with any necessary quoting. A record is a slice of strings with each string being one field. Writes are buffered, so Flush must eventually be called to ensure that the record is written to the underlying io.Writer.

Write将一条CSV记录和任何必要的引号一起写到w中。一个记录是一个字符串的切片,每个字符串是一个字段。写入是缓冲的,所以最终必须调用Flush以确保记录被写入底层的io.Writer。

(*Writer) WriteAll

1
func (w *Writer) WriteAll(records [][]string) error

WriteAll writes multiple CSV records to w using Write and then calls Flush, returning any error from the Flush.

WriteAll使用Write将多个CSV记录写入w,然后调用Flush,返回Flush的任何错误。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package main

import (
	"encoding/csv"
	"log"
	"os"
)

func main() {
	records := [][]string{
		{"first_name", "last_name", "username"},
		{"Rob", "Pike", "rob"},
		{"Ken", "Thompson", "ken"},
		{"Robert", "Griesemer", "gri"},
	}

	w := csv.NewWriter(os.Stdout)
	w.WriteAll(records) // calls Flush internally

	if err := w.Error(); err != nil {
		log.Fatalln("error writing csv:", err)
	}
}

7.7 - encoding

encoding

https://pkg.go.dev/encoding@go1.20.1

Package encoding defines interfaces shared by other packages that convert data to and from byte-level and textual representations. Packages that check for these interfaces include encoding/gob, encoding/json, and encoding/xml. As a result, implementing an interface once can make a type useful in multiple encodings. Standard types that implement these interfaces include time.Time and net.IP. The interfaces come in pairs that produce and consume encoded data.

常量

This section is empty.

变量

This section is empty.

函数

This section is empty.

类型

type BinaryMarshaler

1
2
3
type BinaryMarshaler interface {
	MarshalBinary() (data []byte, err error)
}

BinaryMarshaler is the interface implemented by an object that can marshal itself into a binary form.

MarshalBinary encodes the receiver into a binary form and returns the result.

type BinaryUnmarshaler

1
2
3
type BinaryUnmarshaler interface {
	UnmarshalBinary(data []byte) error
}

BinaryUnmarshaler is the interface implemented by an object that can unmarshal a binary representation of itself.

UnmarshalBinary must be able to decode the form generated by MarshalBinary. UnmarshalBinary must copy the data if it wishes to retain the data after returning.

type TextMarshaler

1
2
3
type TextMarshaler interface {
	MarshalText() (text []byte, err error)
}

TextMarshaler is the interface implemented by an object that can marshal itself into a textual form.

MarshalText encodes the receiver into UTF-8-encoded text and returns the result.

type TextUnmarshaler

1
2
3
type TextUnmarshaler interface {
	UnmarshalText(text []byte) error
}

TextUnmarshaler is the interface implemented by an object that can unmarshal a textual representation of itself.

UnmarshalText must be able to decode the form generated by MarshalText. UnmarshalText must copy the text if it wishes to retain the text after returning.

7.8 - gob

gob

https://pkg.go.dev/encoding/gob@go1.20.1

Package gob manages streams of gobs - binary values exchanged between an Encoder (transmitter) and a Decoder (receiver). A typical use is transporting arguments and results of remote procedure calls (RPCs) such as those provided by package “net/rpc”.

The implementation compiles a custom codec for each data type in the stream and is most efficient when a single Encoder is used to transmit a stream of values, amortizing the cost of compilation.

Basics

A stream of gobs is self-describing. Each data item in the stream is preceded by a specification of its type, expressed in terms of a small set of predefined types. Pointers are not transmitted, but the things they point to are transmitted; that is, the values are flattened. Nil pointers are not permitted, as they have no value. Recursive types work fine, but recursive values (data with cycles) are problematic. This may change.

To use gobs, create an Encoder and present it with a series of data items as values or addresses that can be dereferenced to values. The Encoder makes sure all type information is sent before it is needed. At the receive side, a Decoder retrieves values from the encoded stream and unpacks them into local variables.

类型

The source and destination values/types need not correspond exactly. For structs, fields (identified by name) that are in the source but absent from the receiving variable will be ignored. Fields that are in the receiving variable but missing from the transmitted type or value will be ignored in the destination. If a field with the same name is present in both, their types must be compatible. Both the receiver and transmitter will do all necessary indirection and dereferencing to convert between gobs and actual Go values. For instance, a gob type that is schematically,

struct { A, B int }

can be sent from or received into any of these Go types:

struct { A, B int }	// the same
*struct { A, B int }	// extra indirection of the struct
struct { *A, **B int }	// extra indirection of the fields
struct { A, B int64 }	// different concrete value type; see below

It may also be received into any of these:

struct { A, B int }	// the same
struct { B, A int }	// ordering doesn't matter; matching is by name
struct { A, B, C int }	// extra field (C) ignored
struct { B int }	// missing field (A) ignored; data will be dropped
struct { B, C int }	// missing field (A) ignored; extra field (C) ignored.

Attempting to receive into these types will draw a decode error:

struct { A int; B uint }	// change of signedness for B
struct { A int; B float }	// change of type for B
struct { }			// no field names in common
struct { C, D int }		// no field names in common

Integers are transmitted two ways: arbitrary precision signed integers or arbitrary precision unsigned integers. There is no int8, int16 etc. discrimination in the gob format; there are only signed and unsigned integers. As described below, the transmitter sends the value in a variable-length encoding; the receiver accepts the value and stores it in the destination variable. Floating-point numbers are always sent using IEEE-754 64-bit precision (see below).

Signed integers may be received into any signed integer variable: int, int16, etc.; unsigned integers may be received into any unsigned integer variable; and floating point values may be received into any floating point variable. However, the destination variable must be able to represent the value or the decode operation will fail.

Structs, arrays and slices are also supported. Structs encode and decode only exported fields. Strings and arrays of bytes are supported with a special, efficient representation (see below). When a slice is decoded, if the existing slice has capacity the slice will be extended in place; if not, a new array is allocated. Regardless, the length of the resulting slice reports the number of elements decoded.

In general, if allocation is required, the decoder will allocate memory. If not, it will update the destination variables with values read from the stream. It does not initialize them first, so if the destination is a compound value such as a map, struct, or slice, the decoded values will be merged elementwise into the existing variables.

Functions and channels will not be sent in a gob. Attempting to encode such a value at the top level will fail. A struct field of chan or func type is treated exactly like an unexported field and is ignored.

Gob can encode a value of any type implementing the GobEncoder or encoding.BinaryMarshaler interfaces by calling the corresponding method, in that order of preference.

Gob can decode a value of any type implementing the GobDecoder or encoding.BinaryUnmarshaler interfaces by calling the corresponding method, again in that order of preference.

Encoding Details

This section documents the encoding, details that are not important for most users. Details are presented bottom-up.

An unsigned integer is sent one of two ways. If it is less than 128, it is sent as a byte with that value. Otherwise it is sent as a minimal-length big-endian (high byte first) byte stream holding the value, preceded by one byte holding the byte count, negated. Thus 0 is transmitted as (00), 7 is transmitted as (07) and 256 is transmitted as (FE 01 00).

A boolean is encoded within an unsigned integer: 0 for false, 1 for true.

A signed integer, i, is encoded within an unsigned integer, u. Within u, bits 1 upward contain the value; bit 0 says whether they should be complemented upon receipt. The encode algorithm looks like this:

1
2
3
4
5
6
7
var u uint
if i < 0 {
	u = (^uint(i) << 1) | 1 // complement i, bit 0 is 1
} else {
	u = (uint(i) << 1) // do not complement i, bit 0 is 0
}
encodeUnsigned(u)

The low bit is therefore analogous to a sign bit, but making it the complement bit instead guarantees that the largest negative integer is not a special case. For example, -129=^128=(^256»1) encodes as (FE 01 01).

Floating-point numbers are always sent as a representation of a float64 value. That value is converted to a uint64 using math.Float64bits. The uint64 is then byte-reversed and sent as a regular unsigned integer. The byte-reversal means the exponent and high-precision part of the mantissa go first. Since the low bits are often zero, this can save encoding bytes. For instance, 17.0 is encoded in only three bytes (FE 31 40).

Strings and slices of bytes are sent as an unsigned count followed by that many uninterpreted bytes of the value.

All other slices and arrays are sent as an unsigned count followed by that many elements using the standard gob encoding for their type, recursively.

Maps are sent as an unsigned count followed by that many key, element pairs. Empty but non-nil maps are sent, so if the receiver has not allocated one already, one will always be allocated on receipt unless the transmitted map is nil and not at the top level.

In slices and arrays, as well as maps, all elements, even zero-valued elements, are transmitted, even if all the elements are zero.

Structs are sent as a sequence of (field number, field value) pairs. The field value is sent using the standard gob encoding for its type, recursively. If a field has the zero value for its type (except for arrays; see above), it is omitted from the transmission. The field number is defined by the type of the encoded struct: the first field of the encoded type is field 0, the second is field 1, etc. When encoding a value, the field numbers are delta encoded for efficiency and the fields are always sent in order of increasing field number; the deltas are therefore unsigned. The initialization for the delta encoding sets the field number to -1, so an unsigned integer field 0 with value 7 is transmitted as unsigned delta = 1, unsigned value = 7 or (01 07). Finally, after all the fields have been sent a terminating mark denotes the end of the struct. That mark is a delta=0 value, which has representation (00).

Interface types are not checked for compatibility; all interface types are treated, for transmission, as members of a single “interface” type, analogous to int or []byte - in effect they’re all treated as interface{}. Interface values are transmitted as a string identifying the concrete type being sent (a name that must be pre-defined by calling Register), followed by a byte count of the length of the following data (so the value can be skipped if it cannot be stored), followed by the usual encoding of concrete (dynamic) value stored in the interface value. (A nil interface value is identified by the empty string and transmits no value.) Upon receipt, the decoder verifies that the unpacked concrete item satisfies the interface of the receiving variable.

If a value is passed to Encode and the type is not a struct (or pointer to struct, etc.), for simplicity of processing it is represented as a struct of one field. The only visible effect of this is to encode a zero byte after the value, just as after the last field of an encoded struct, so that the decode algorithm knows when the top-level value is complete.

The representation of types is described below. When a type is defined on a given connection between an Encoder and Decoder, it is assigned a signed integer type id. When Encoder.Encode(v) is called, it makes sure there is an id assigned for the type of v and all its elements and then it sends the pair (typeid, encoded-v) where typeid is the type id of the encoded type of v and encoded-v is the gob encoding of the value v.

To define a type, the encoder chooses an unused, positive type id and sends the pair (-type id, encoded-type) where encoded-type is the gob encoding of a wireType description, constructed from these types:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
type wireType struct {
	ArrayT           *ArrayType
	SliceT           *SliceType
	StructT          *StructType
	MapT             *MapType
	GobEncoderT      *gobEncoderType
	BinaryMarshalerT *gobEncoderType
	TextMarshalerT   *gobEncoderType

}
type arrayType struct {
	CommonType
	Elem typeId
	Len  int
}
type CommonType struct {
	Name string // the name of the struct type
	Id  int    // the id of the type, repeated so it's inside the type
}
type sliceType struct {
	CommonType
	Elem typeId
}
type structType struct {
	CommonType
	Field []*fieldType // the fields of the struct.
}
type fieldType struct {
	Name string // the name of the field.
	Id   int    // the type id of the field, which must be already defined
}
type mapType struct {
	CommonType
	Key  typeId
	Elem typeId
}
type gobEncoderType struct {
	CommonType
}

If there are nested type ids, the types for all inner type ids must be defined before the top-level type id is used to describe an encoded-v.

For simplicity in setup, the connection is defined to understand these types a priori, as well as the basic gob types int, uint, etc. Their ids are:

bool        1
int         2
uint        3
float       4
[]byte      5
string      6
complex     7
interface   8
// gap for reserved ids.
WireType    16
ArrayType   17
CommonType  18
SliceType   19
StructType  20
FieldType   21
// 22 is slice of fieldType.
MapType     23

Finally, each message created by a call to Encode is preceded by an encoded unsigned integer count of the number of bytes remaining in the message. After the initial type name, interface values are wrapped the same way; in effect, the interface value acts like a recursive invocation of Encode.

In summary, a gob stream looks like

(byteCount (-type id, encoding of a wireType)* (type id, encoding of a value))*

where * signifies zero or more repetitions and the type id of a value must be predefined or be defined before the value in the stream.

Compatibility: Any future changes to the package will endeavor to maintain compatibility with streams encoded using previous versions. That is, any released version of this package should be able to decode data written with any previously released version, subject to issues such as security fixes. See the Go compatibility document for background: https://golang.org/doc/go1compat

See “Gobs of data” for a design discussion of the gob wire format: https://blog.golang.org/gobs-of-data

Security

This package is not designed to be hardened against adversarial inputs, and is outside the scope of https://go.dev/security/policy. In particular, the Decoder does only basic sanity checking on decoded input sizes, and its limits are not configurable. Care should be taken when decoding gob data from untrusted sources, which may consume significant resources.

Example
Example
Example

常量

This section is empty.

变量

This section is empty.

函数

func Register

1
func Register(value any)

Register records a type, identified by a value for that type, under its internal type name. That name will identify the concrete type of a value sent or received as an interface variable. Only types that will be transferred as implementations of interface values need to be registered. Expecting to be used only during initialization, it panics if the mapping between types and names is not a bijection.

func RegisterName

1
func RegisterName(name string, value any)

RegisterName is like Register but uses the provided name rather than the type’s default.

类型

type CommonType

1
2
3
4
type CommonType struct {
	Name string
	Id   typeId
}

CommonType holds elements of all types. It is a historical artifact, kept for binary compatibility and exported only for the benefit of the package’s encoding of type descriptors. It is not intended for direct use by clients.

type Decoder

1
2
3
type Decoder struct {
	// contains filtered or unexported fields
}

A Decoder manages the receipt of type and data information read from the remote side of a connection. It is safe for concurrent use by multiple goroutines.

The Decoder does only basic sanity checking on decoded input sizes, and its limits are not configurable. Take caution when decoding gob data from untrusted sources.

func NewDecoder

1
func NewDecoder(r io.Reader) *Decoder

NewDecoder returns a new decoder that reads from the io.Reader. If r does not also implement io.ByteReader, it will be wrapped in a bufio.Reader.

(*Decoder) Decode

1
func (dec *Decoder) Decode(e any) error

Decode reads the next value from the input stream and stores it in the data represented by the empty interface value. If e is nil, the value will be discarded. Otherwise, the value underlying e must be a pointer to the correct type for the next data item received. If the input is at EOF, Decode returns io.EOF and does not modify e.

(*Decoder) DecodeValue

1
func (dec *Decoder) DecodeValue(v reflect.Value) error

DecodeValue reads the next value from the input stream. If v is the zero reflect.Value (v.Kind() == Invalid), DecodeValue discards the value. Otherwise, it stores the value into v. In that case, v must represent a non-nil pointer to data or be an assignable reflect.Value (v.CanSet()) If the input is at EOF, DecodeValue returns io.EOF and does not modify v.

type Encoder

1
2
3
type Encoder struct {
	// contains filtered or unexported fields
}

An Encoder manages the transmission of type and data information to the other side of a connection. It is safe for concurrent use by multiple goroutines.

func NewEncoder

1
func NewEncoder(w io.Writer) *Encoder

NewEncoder returns a new encoder that will transmit on the io.Writer.

(*Encoder) Encode

1
func (enc *Encoder) Encode(e any) error

Encode transmits the data item represented by the empty interface value, guaranteeing that all necessary type information has been transmitted first. Passing a nil pointer to Encoder will panic, as they cannot be transmitted by gob.

(*Encoder) EncodeValue

1
func (enc *Encoder) EncodeValue(value reflect.Value) error

EncodeValue transmits the data item represented by the reflection value, guaranteeing that all necessary type information has been transmitted first. Passing a nil pointer to EncodeValue will panic, as they cannot be transmitted by gob.

type GobDecoder

1
2
3
4
5
6
type GobDecoder interface {
	// GobDecode overwrites the receiver, which must be a pointer,
	// with the value represented by the byte slice, which was written
	// by GobEncode, usually for the same concrete type.
	GobDecode([]byte) error
}

GobDecoder is the interface describing data that provides its own routine for decoding transmitted values sent by a GobEncoder.

type GobEncoder

1
2
3
4
5
6
type GobEncoder interface {
	// GobEncode returns a byte slice representing the encoding of the
	// receiver for transmission to a GobDecoder, usually of the same
	// concrete type.
	GobEncode() ([]byte, error)
}

GobEncoder is the interface describing data that provides its own representation for encoding values for transmission to a GobDecoder. A type that implements GobEncoder and GobDecoder has complete control over the representation of its data and may therefore contain things such as private fields, channels, and functions, which are not usually transmissible in gob streams.

Note: Since gobs can be stored permanently, it is good design to guarantee the encoding used by a GobEncoder is stable as the software evolves. For instance, it might make sense for GobEncode to include a version number in the encoding.

7.9 - hex

hex

https://pkg.go.dev/encoding/hex@go1.20.1

Package hex implements hexadecimal encoding and decoding.

包hex实现了十六进制的编码和解码。

常量

This section is empty.

变量

View Source

1
var ErrLength = errors.New("encoding/hex: odd length hex string")

ErrLength reports an attempt to decode an odd-length input using Decode or DecodeString. The stream-based Decoder returns io.ErrUnexpectedEOF instead of ErrLength.

ErrLength报告使用Decode或DecodeString解码一个奇长的输入的尝试。基于流的解码器返回io.ErrUnexpectedEOF而不是ErrLength。

函数

func Decode

1
func Decode(dst, src []byte) (int, error)

Decode decodes src into DecodedLen(len(src)) bytes, returning the actual number of bytes written to dst.

Decode将src解码为DecodedLen(len(src))字节,返回写给dst的实际字节数。

Decode expects that src contains only hexadecimal characters and that src has even length. If the input is malformed, Decode returns the number of bytes decoded before the error.

解码期望src只包含十六进制的字符,并且src的长度是偶数。如果输入是畸形的,Decode会返回错误发生前的解码字节数。

Example

func DecodeString

1
func DecodeString(s string) ([]byte, error)

DecodeString returns the bytes represented by the hexadecimal string s.

DecodeString返回十六进制字符串s所代表的字节数。

DecodeString expects that src contains only hexadecimal characters and that src has even length. If the input is malformed, DecodeString returns the bytes decoded before the error.

DecodeString期望src只包含十六进制的字符,并且src具有偶数长度。如果输入是畸形的,DecodeString将返回错误之前的解码字节。

Example

func DecodedLen

1
func DecodedLen(x int) int

DecodedLen returns the length of a decoding of x source bytes. Specifically, it returns x / 2.

DecodedLen返回x个源字节的解码长度。具体来说,它返回x/2。

func Dump

1
func Dump(data []byte) string

Dump returns a string that contains a hex dump of the given data. The format of the hex dump matches the output of hexdump -C on the command line.

Dump返回一个包含给定数据的十六进制转储的字符串。十六进制转储的格式与命令行中hexdump -C的输出相匹配。

Example

func Dumper

1
func Dumper(w io.Writer) io.WriteCloser

Dumper returns a WriteCloser that writes a hex dump of all written data to w. The format of the dump matches the output of hexdump -C on the command line.

Dumper返回一个WriteCloser,将所有写入的数据的十六进制转储到w。

Example

func Encode

1
func Encode(dst, src []byte) int

Encode encodes src into EncodedLen(len(src)) bytes of dst. As a convenience, it returns the number of bytes written to dst, but this value is always EncodedLen(len(src)). Encode implements hexadecimal encoding.

Encode将src编码为dst的EncodedLen(len(src))字节。为了方便起见,它返回写入dst的字节数,但这个值总是EncodedLen(len(src))。Encode实现了十六进制的编码。

Example

func EncodeToString

1
func EncodeToString(src []byte) string

EncodeToString returns the hexadecimal encoding of src.

EncodeToString返回src的十六进制编码。

Example

func EncodedLen

1
func EncodedLen(n int) int

EncodedLen returns the length of an encoding of n source bytes. Specifically, it returns n * 2.

EncodedLen返回n个源字节的编码的长度。具体来说,它返回n * 2。

func NewDecoder <- go1.10

1
func NewDecoder(r io.Reader) io.Reader

NewDecoder returns an io.Reader that decodes hexadecimal characters from r. NewDecoder expects that r contain only an even number of hexadecimal characters.

NewDecoder返回一个io.Reader,对r中的十六进制字符进行解码。NewDecoder希望r中只包含偶数的十六进制字符。

func NewEncoder <- go1.10

1
func NewEncoder(w io.Writer) io.Writer

NewEncoder returns an io.Writer that writes lowercase hexadecimal characters to w.

NewEncoder返回一个io.Writer,将小写的十六进制字符写入w中。

类型

type InvalidByteError

1
type InvalidByteError byte

InvalidByteError values describe errors resulting from an invalid byte in a hex string.

InvalidByteError值描述由十六进制字符串中的无效字节导致的错误。

(InvalidByteError) Error

1
func (e InvalidByteError) Error() string

7.10 - json

json

https://pkg.go.dev/encoding/json@go1.20.1

​ json包实现了RFC 7159中定义的JSON编解码。JSON和Go值之间的映射在Marshal和Unmarshal函数的文档中有描述。

​ 有关此包的介绍,请参见JSON和Go

Example (CustomMarshalJSON)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package main

import (
	"encoding/json"
	"fmt"
	"log"
	"strings"
)

type Animal int

const (
	Unknown Animal = iota
	Gopher
	Zebra
)

func (a *Animal) UnmarshalJSON(b []byte) error {
	var s string
	if err := json.Unmarshal(b, &s); err != nil {
		return err
	}
	switch strings.ToLower(s) {
	default:
		*a = Unknown
	case "gopher":
		*a = Gopher
	case "zebra":
		*a = Zebra
	}

	return nil
}

func (a Animal) MarshalJSON() ([]byte, error) {
	var s string
	switch a {
	default:
		s = "unknown"
	case Gopher:
		s = "gopher"
	case Zebra:
		s = "zebra"
	}

	return json.Marshal(s)
}

func main() {
	blob := `["gopher","armadillo","zebra","unknown","gopher","bee","gopher","zebra"]`
	var zoo []Animal
	if err := json.Unmarshal([]byte(blob), &zoo); err != nil {
		log.Fatal(err)
	}

	census := make(map[Animal]int)
	for _, animal := range zoo {
		census[animal] += 1
	}

	fmt.Printf("Zoo Census:\n* Gophers: %d\n* Zebras:  %d\n* Unknown: %d\n",
		census[Gopher], census[Zebra], census[Unknown])

}
Output:

Zoo Census:
* Gophers: 3
* Zebras:  2
* Unknown: 3
Example(TextMarshalJSON)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package main

import (
	"encoding/json"
	"fmt"
	"log"
	"strings"
)

type Size int

const (
	Unrecognized Size = iota
	Small
	Large
)

func (s *Size) UnmarshalText(text []byte) error {
	switch strings.ToLower(string(text)) {
	default:
		*s = Unrecognized
	case "small":
		*s = Small
	case "large":
		*s = Large
	}
	return nil
}

func (s Size) MarshalText() ([]byte, error) {
	var name string
	switch s {
	default:
		name = "unrecognized"
	case Small:
		name = "small"
	case Large:
		name = "large"
	}
	return []byte(name), nil
}

func main() {
	blob := `["small","regular","large","unrecognized","small","normal","small","large"]`
	var inventory []Size
	if err := json.Unmarshal([]byte(blob), &inventory); err != nil {
		log.Fatal(err)
	}

	counts := make(map[Size]int)
	for _, size := range inventory {
		counts[size] += 1
	}

	fmt.Printf("Inventory Counts:\n* Small:        %d\n* Large:        %d\n* Unrecognized: %d\n",
		counts[Small], counts[Large], counts[Unrecognized])

}
Output:

Inventory Counts:
* Small:        3
* Large:        2
* Unrecognized: 3

常量

This section is empty.

变量

This section is empty.

函数

func Compact

1
func Compact(dst *bytes.Buffer, src []byte) error

​ Compact函数将JSON编码的src附加到dst中,省略了不重要的空格字符。

func HTMLEscape

1
func HTMLEscape(dst *bytes.Buffer, src []byte)

​ HTMLEscape函数将JSON编码的src附加到dst中,将字符串文字内的<、>、&、U+2028和U+2029字符更改为\u003c、\u003e、\u0026、\u2028、\u2029,以使JSON可以安全地嵌入HTML <script>标记中。由于历史原因,Web浏览器不支持在<script>标记中使用标准的HTML转义,因此必须使用替代的JSON编码。

HTMLEscape Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
package main

import (
	"bytes"
	"encoding/json"
	"os"
)

func main() {
	var out bytes.Buffer
	json.HTMLEscape(&out, []byte(`{"Name":"<b>HTML content</b>"}`))
	out.WriteTo(os.Stdout)
}
Output:

{"Name":"\u003cb\u003eHTML content\u003c/b\u003e"}

func Indent

1
func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error

​ Indent函数将JSON编码的src的缩进形式附加到dst中。JSON对象或数组中的每个元素都在新的缩进行上开始,该行以prefix开头,后跟一个或多个indent的副本,具体取决于缩进嵌套。附加到dst的数据不以prefix或任何缩进开始,以使其更容易嵌入其他格式化的JSON数据中。虽然src开头的前导空格字符(空格、制表符、回车、换行符)会被删除,但src末尾的尾随空格字符会被保留并复制到dst中。例如,如果src没有尾随空格,则dst也没有;如果src以尾随换行符结束,则dst也是如此。

Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package main

import (
	"bytes"
	"encoding/json"
	"log"
	"os"
)

func main() {
	type Road struct {
		Name   string
		Number int
	}
	roads := []Road{
		{"Diamond Fork", 29},
		{"Sheep Creek", 51},
	}

	b, err := json.Marshal(roads)
	if err != nil {
		log.Fatal(err)
	}

	var out bytes.Buffer
	json.Indent(&out, b, "=", "\t")
	out.WriteTo(os.Stdout)
}
Output:

[
=	{
=		"Name": "Diamond Fork",
=		"Number": 29
=	},
=	{
=		"Name": "Sheep Creek",
=		"Number": 51
=	}
=]

func Marshal

1
func Marshal(v any) ([]byte, error)

​ Marshal函数返回v的JSON编码。

​ Marshal函数递归遍历值v。如果遇到的值实现了Marshaler接口并且不是nil指针,则Marshal调用其MarshalJSON方法以生成JSON。如果没有MarshalJSON方法但该值代替实现了encoding.TextMarshaler,则Marshal调用其MarshalText方法并将结果编码为JSON字符串。nil指针异常并不是严格必要的,但模仿了在UnmarshalJSON的行为中必要的类似异常。

​ 否则,Marshal使用以下类型相关的默认编码:

​ 布尔值被编码为JSON布尔值。

​ 浮点数、整数和Number类型的值被编码为JSON数字。

​ 字符串类型的值被编码为JSON字符串,被强制转换为有效的UTF-8编码,无效的字节会被替换为Unicode替换符。为了将JSON安全地嵌入到HTML的